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

↘锁芯ラ 提交于 2019-12-22 04:56:16

问题


I have a part of code who works as expected on all iOS versions, but not on iOS 9:

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

It's a simple json text.

I got this error:

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

How this url can be intepreted as a file ? Response = nil...

Thanks.


回答1:


Technically is it because of the changes of NSURLSession of networking in iOS9. To fix your issue, you need to go to app's info.plist, NSAppTransportSecurity [Dictionary] needs to have a key NSAllowsArbitraryLoads [Boolean] to be set to YES or call urls with https.

You can see more about changes of NSURLSession of networking in iOS9 in http://devstreaming.apple.com/videos/wwdc/2015/711y6zlz0ll/711/711_networking_with_nsurlsession.pdf?dl=1




回答2:


After debugging for 3 hours, I avoided the bug alltogether by using asynchronous NSMutableURLRequest, which I also observed is way faster than the synchronous 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()


来源:https://stackoverflow.com/questions/31903390/strange-bug-with-xcode-7-ios-9-b5-with-datawithcontentsofurl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!