Xcode 7 / iOS 9 b5与dataWithContentsOfURL的奇怪(bug?)

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

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

这是一个简单的JSON文本。

我得到这个错误:

错误域= NSCocoaErrorDomain代码= 256“文件”xxx.php“无法打开。 UserInfo = {NSURL = http://xxx.xxx.com/xxx/xxx.php?lang=fr }

这个URL如何被解释为一个文件? 回应=无…

谢谢。

从技术上讲,是因为iOS9networking的NSURLSession的变化。 要解决你的问题,你需要去应用程序的info.plist,NSAppTransportSecurity [Dictionary]需要有一个关键NSAllowsArbitraryLoads [布尔]被设置为YES或用https调用URL。

你可以在http://devstreaming.apple.com/videos/wwdc/2015/711y6zlz0ll/711/711_networking_with_nsurlsession.pdf?dl=1上看到更多关于iOS9networking的NSURLSession的变化

经过3个小时的debugging,我通过使用asynchronousNSMutableURLRequest来避免所有的bug,我也观察到比同步的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()