I just had gone through the tutorial for setting up my first test iOS app in Xcode. All that went well. I have done a lot of web site development, I am very familiar with making data requests. I have an ubuntu server in the cloud that I want to use to return data to the app.
What is the best way to do this?
I tried setting up a basic http request, but I got an error saying that iOS by default doesn't allow non-secure connections. I then set up HTTPS on my server, and confirmed that I can get the data through the web browser, even though it warns me that the certificate isn't trusted. OK, so then from my iOS app and it gives me some errors about NSURLErrorFailingURLPeerTrustErrorKey
and even one line returned saying: NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?
. All my code is here right now:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, NSURLSessionDelegate {
// MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var mealNameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Handle the text field’s user input through delegate callbacks.
nameTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
mealNameLabel.text = nameTextField.text
}
// MARK: Actions
@IBAction func setDefaultLabelText(sender: UIButton) {
mealNameLabel.text = "Default Text"
post_request()
}
func post_request(){
let request = NSMutableURLRequest(URL: NSURL(string: "https://54.164.XXX.XX/post_script.php")!)
request.HTTPMethod = "POST"
let postString = "id=13&name=Jack"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}
}
So what is the best way to set up the data request? Is HTTPS the only option? Is it possible to make a secure connection to get data without buying a proper ssl certificate? I mean I connect to servers with ssh all the time and its free. What are the options for getting data from a server with iOS?