How to use NSURLSession's dataTaskWithURL with Swift 2?

3.8k views Asked by At

While using Swift 1 this code worked fine:

        let connectionSession = NSURLSession.sharedSession()

        let task = connectionSession.dataTaskWithURL(currentURL!,  completionHandler:  { (data, response , error) in
            ...

In Swift 2 I am getting the following compiler error:

Invalid conversion from throwing function of type '(_, _, _) throws -> _' to non-throwing function type '(NSData?, NSURLResponse?, NSError?) -> Void'

How can I fix this?

4

There are 4 answers

0
Özgür Ersil On

you can use with the optional values like that

 var task = session.dataTaskWithURL(url!) {
        (NSData?, NSURLResponse?, NSError?) throws -> Void

           do {
             var jsonData = try NSJSONSerialization.JSONObjectWithData(data!,options: .MutableContainers) as! NSArray

           } catch {
          // handle error
           }
 }

 task!.resume()
0
Georg Tuparev On

As @MartinR pointed out, it turned out that the problem was not in the call of NSURLSession's dataTaskWithURL but deep down in the completion handler (more specifically, one of the added during the Swift 1 -> Swift 2 conversions 'try' had not corresponding catch). I have seen others also having similar problems (questions at personal blogs) and will file enhancement request to the Swift folks for better error description.

0
Gerd Castan On

In Swift 2, XCode 7, Apple replaced NSError with ErrorType in several APIs (not all).

You probably use NSError in your own code explicitly. Replace your own NSError usage with ErrorType where Apple uses ErrorType.

0
jrc On

To use NSJSONSerialization.JSONObjectWithData within the completion handler, you will need catch errors:

    do {
        var jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSArray
        // Do Stuff
    } catch {
        // handle error
    }