How to use dataWithRequest in Swift 2?

let session = NSURLSession.sharedSession()
if let url = NSURL(string: someURL) {
    let request = NSMutableURLRequest(URL: url)
    let task = session.dataTaskWithRequest(request) { (data, response, error) in
          if data != nil {
              print(NSString(data: data, encoding: NSUTF8StringEncoding))
          }
    }
    task?.resume()
}


This one works fine on Swift 1.2 ( with println and task.resume() ) and I was able to get the data as I expected.

But, when I run this code on Swift 2 (Xcode 7) I got rejected from the server. What is the correct way to implement this in Swift 2.0?

Replies

What is the nature of the rejection? Note that there is a bug in recent versions of NSURLSession (both Yosemite and iOS 8) where the Content-Type needs to be set explicitly in the request — any value specified in the default headers isn't honored.

There may also be an issue with the new App Transport Security feature of iOS 9.0 and OS X 10.11, which might be forcing your connection to go over https and result in errors if the server you are contacting doesn't offer compatible support.


https://developer.apple.com/library/prerelease/ios/technotes/App-Transport-Security-Technote/index.html


https://forums.developer.apple.com/thread/3544