Nsurlconnection Throws After Updating to Swift 2.0

Issue Getting NSData Request To Work In Swift 2.0

If you are working with Swift 2, you should not pass the last argument "error". Instead put a try around the NSData initialization. If data needs to be accessed outside take the init result in a var and convert to let Modified code

var optData:NSData? = nil
do {
optData = try NSData(contentsOfURL: dataURL!, options: NSDataReadingOptions.DataReadingMappedIfSafe)
}
catch {
print("Handle \(error) here")
}

if let data = optData {
// Convert data to JSON here
}

Swift 2 NSURLSession.sharedSession().dataTaskWithURL Cannot invoke with an argument list of type

The compiler is throwing the following error:

/Users/Xcode/Desktop/fdsfsdfds/fdsfsdfds/AppDelegate.swift:24:28:
Cannot invoke 'dataTaskWithURL' with an argument list of type '(NSURL,
(_, _, _) throws -> Void)'

In the completionHandler you're not catching the exceptions that JSONObjectWithData may eventually throw. Therefore the compiler infers that you're trying to propagate the exception which would require that the completionHandler had the following signature:

(NSData?, NSURLResponse?, NSError?) throws -> Void

This does not match with the actual completionHandler dataTaskWithURL is expecting and thus the error.

To solve this issue simply wrap your call to NSJSONSerialization.JSONObjectWithData is a do/catch statement as follows to handle the error:

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

} catch {
// handle error
}

For more informations about error handling in Swift2 refer to the prerelease documentation available here



Related Topics



Leave a reply



Submit