奇怪(错误?)与 Xcode 7 / iOS 9 b5 与 dataWithContentsOfURL

Strange (bug ?) with Xcode 7 / iOS 9 b5 with dataWithContentsOfURL

我有一部分代码在所有 iOS 版本上都按预期工作,但在 iOS 9 上没有:

NSData *response = [NSData dataWithContentsOfURL: [NSURL URLWithString: url] options:NSDataReadingUncached error:&error];

这是一个简单的 json 文本。

我收到这个错误:

Error Domain=NSCocoaErrorDomain Code=256 "The file “xxx.php” couldn’t be opened." UserInfo={NSURL=http://xxx.xxx.com/xxx/xxx.php?lang=fr}

如何将此 url 解释为文件?响应 = 无...

谢谢。

从技术上讲是因为 iOS9 中网络的 NSURLSession 发生了变化。 要解决您的问题,您需要转到应用程序的 info.plist,NSAppTransportSecurity [Dictionary] 需要将键 NSAllowsArbitraryLoads [Boolean] 设置为 YES 或使用 https 调用 url。

您可以在http://devstreaming.apple.com/videos/wwdc/2015/711y6zlz0ll/711/711_networking_with_nsurlsession.pdf?dl=1

中的iOS9中查看更多关于网络NSURLSession的变化

调试了 3 小时后,我通过使用异步 NSMutableURLRequest 完全避免了这个错误,我还观察到它比同步 NSData 快得多。

let requestURL: NSURL = NSURL(string: url)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
    (data, response, error) -> Void in
    if error == nil {
        var response = UIImage(data:data!)
    } else {
        NSLog("Fail")
    }
}
task.resume()