iOS Swift Tutorial iOS9 Swift2

NSURLSession changes in iOS9

I am sure anyone who started with iOS app development would have dealt with NSURLSession. In this post I wanted to tell you about the changes to NSURLSession in iOS9 for security reason. Lets take a look at this sample code.
The code used to work perfectly fine in iOS8 but in iOS9 the code breaks and throws NSURLDomainError or CFNetwork SSLHandshake failed (-9824)

        let baseURL = NSURL(string: "https://itunes.apple.com/search?term=one%20republic")
        let downloadTask = session.downloadTaskWithURL(baseURL!, completionHandler: { (location, response, error) -> Void in
            if(error == nil){
                let objectData = NSData(contentsOfURL: location!)
                let tmpData :NSString = NSString(data: objectData!, encoding: NSUTF8StringEncoding)!
                print("success")
            } else {
                print("Failed")
            }
            
        })
        downloadTask!.resume()

This is because of the new security features in NSURLSession in iOS9. Take a look at this video for more information https://developer.apple.com/videos/wwdc/2015/?id=711

You can fix this code by adding the NSAppTransportSecurity to the Info.plist with setting NSAllowsArbitraryLoads to true. Don’t do this unless you know what you are doing and why you are doing it.

Screen Shot 2015-06-18 at 8.24.19 AM
App transport security is added to improve the security of the app.  The best bet would be to add ssl support for your server. If you don’t have control over it I would suggest  taking the below mentioned approach instead of the blanket solution.

NSAppTransportSecurity

  NSExceptionDomains
  
    yourserver.com
    
      <!--Include to allow subdomains-->
      NSIncludesSubdomains
      
      <!--Include to allow insecure HTTP requests-->
      NSTemporaryExceptionAllowsInsecureHTTPLoads
      
      <!--Include to specify minimum TLS version-->
      NSTemporaryExceptionMinimumTLSVersion
      TLSv1.1
    
  

 

For some reason I am not able to fetch the data from itunes without adding the keys to the Info.plist. Am I missing something?

About the author

Shrikar

Backend/Infrastructure Engineer by Day. iOS Developer for the rest of the time.

  • leversol

    Thanks for the tutorial. I also tested and I have not got the data that once exceptiona was added to the plist file. Test with the URL http://www.google.com and you will get the answer without exceptions ( Infact, it was mentioned in the video of Apple)

  • Ramakrishna Lova

    Thanks for the tutorial !

  • Cliff

    I receive the following error in playground

/* ]]> */