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

2019-04-26 03:10发布

问题:

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()


标签: ios xcode7 ios9