第一个iOS应用程序,正确的方式来查询我的服务器



我刚刚完成了在Xcode中设置我的第一个测试iOS应用程序的教程。一切进展顺利。我做了很多网站开发,我非常熟悉数据请求。我在云中有一个ubuntu服务器,我想用它向应用程序返回数据。

最好的方法是什么?

我尝试设置一个基本的http请求,但我收到一个错误,说iOS默认不允许非安全连接。然后,我在服务器上设置了HTTPS,并确认我可以通过网络浏览器获取数据,尽管它警告我证书不可信。好吧,然后从我的iOS应用程序中,它给了我一些关于NSURLErrorFailingURLPeerTrustErrorKey的错误,甚至返回了一行:NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?。我所有的代码现在都在这里:

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()
    }
}

那么,设置数据请求的最佳方式是什么呢?HTTPS是唯一的选择吗?是否可以在不购买正确的ssl证书的情况下进行安全连接以获取数据?我的意思是,我一直用ssh连接服务器,而且是免费的。从iOS服务器获取数据的选项有哪些?

这是iOS的常见问题,您必须连接到正确的SSL证书。iOS中曾经有隐藏的类,可以让你连接到非标准网站,这在测试过程中很有帮助,但这些类必须在发布前删除,否则苹果会拒绝。

最后的答案是,如果你必须使用SSL(https),网站必须有一个有效/正确的SSL证书。

顺便说一句,如果iOS默认不允许,那么你似乎可以更改你的应用程序(权限?)以允许它。我建议尝试这样做,因为安全通信在任何时候都不是必要的。

相关内容

最新更新