我正在制作一个基本的"你好世界" iOS应用。我在云中有一个ubuntu服务器,我想从iOS应用程序查询。我知道服务器需要是安全的,即需要通过https请求访问,服务器上的证书需要被信任"。
现在我想要做的就是覆盖这个要求。我有一个自签名证书,适用于我服务器上的https。当我使用iOS应用程序发出请求时,它会给我一些关于NSURLErrorFailingURLPeerTrustErrorKey
的错误,甚至还有一行返回说:NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?
。
我知道这是一个常见问题,本网站上有许多关于如何处理它的主题。我尝试了this post的一段代码。我把这篇文章添加到我的代码中:
func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust{
let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential,credential);
}
}
我的整个ViewController代码在这里:
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()
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust{
let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential,credential);
}
}
}
看起来这个想法是从连接中获取challenge
事件,并告诉它"是的我想继续"。但这段代码似乎没有被调用。邮件请求已发送,但我收到有关不受信任证书的错误消息。有人可以帮我修改我的代码,以便我可以从我的服务器接受这个证书吗?
答案 0 :(得分:2)
您需要让ViewController NSURLSessionDelegate
接收回调,并将会话的委托设置为您的控制器,如下所示:
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
...
let task = session.dataTaskWithRequest(request) { data, response, error in
}
task.resume()
答案 1 :(得分:1)
您无法使用共享会话来获取这些委托方法。您必须实例化一个新的NSURLSession
并将自己声明为委托。
// Delegate methods won't be callend
let task = NSURLSession.sharedSession()...
// Use this to get delegate calls
let task = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: self,
delegateQueue: /* make a queue */)...
使用iOS 9,您还需要查看NSAppTransportSecurity并将这些键添加到您的plist中。 iOS 9中需要这些以允许SSL连接。