7

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.

skrew
  • 879
  • 9
  • 16

2 Answers2

10

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

AmeenD
  • 130
  • 1
  • 6
  • 1
    C&P version: `NSAppTransportSecurity NSAllowsArbitraryLoads ` – bk138 Sep 10 '15 at 16:11
  • Do not do this! If you do this, you are essentially defeating the additional security features of "App Transport Security" introduced in iOS9. Instead see this answer: http://stackoverflow.com/a/30836686/505093 – kwahn Sep 22 '15 at 20:01
0

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()
Nicoara Talpes
  • 710
  • 1
  • 13
  • 28