【发布时间】:2015-10-14 14:33:02
【问题描述】:
我正在使用 Xcode 7、Swift 2 和 iOS9。我想使用 NSURLSession 连接到 Web 服务,但尝试连接时出现以下错误:
2015-10-13 16:07:33.595 XCTRunner[89220:4520715] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
2015-10-13 16:07:33.604 XCTRunner[89220:4520571] Error with connection, details: Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “domainapi.com” which could put your confidential information at risk." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x7fac7b6facc0>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?,
这是我的代码:
func request( dataPost : String, successHandler: (response: String) -> Void)-> String {
let destination:String = "https://domainapi.com:8743/WebService/sendData"
let request = NSMutableURLRequest(URL: NSURL(string: destination as String)!)
request.HTTPMethod = "POST"
let postString = dataPost
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
request.setValue("0", forHTTPHeaderField: "Content-Length")
request.setValue("application/xml", forHTTPHeaderField: "Content-Type")
request.setValue("gzip,deflate", forHTTPHeaderField: "Accept-Encoding")
request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
NSLog("Body is: %@", request.HTTPBody!)
NSLog("Request is: %@", request.allHTTPHeaderFields!)
NSLog("URL is: %@", destination)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
NSLog("Error with connection, details: %@", error!)
return
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
successHandler(response: responseString as String!);
NSLog("Data received: %@", data!)
}
task.resume()
return "worked"
}
func viewDidLoad() {
let dataPost : String = "<webservices>xml data sending</webservices>"
request(dataPost, successHandler: {
(response) in
let text = response
print(text)
});
我已经查看了NSURLAuthenticationChallenge,但我似乎无法用我目前拥有的代码来解决这个问题。所以我的问题是我如何才能连接到服务器?我已经尝试在 Info.plist 中将域添加到我的NSAppTransportSecurity 中,但这不起作用。打开NSAllowsArbitraryLoads 也不起作用。任何帮助将不胜感激。
【问题讨论】:
-
在 SO 上查看这个问题:stackoverflow.com/questions/933331/…
-
@ZoffDino 正在使用 iOS8 中已弃用的 NSURLConnection。如果可能,我想使用 NSURLSession。
-
AFNetworking 库对此提供了出色的支持,我建议您查看一下。
标签: xcode swift swift2 ios9 xcode7