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
iOS 12 Wkwebview Not Working with Redirects
Why Would One Use Nested Classes
Iocreateplugininterfaceforservice Returns Mysterious Error
Wkwebview Won't Load (Nsviewcontroller, Os X)
Get Png Representation of Nsimage in Swift
Decoding a Nested Array in Swift 4
Remove from Array of Anycancellable When Publisher Finishes
Variable with Getter/Setter Cannot Have Initial Value, on Overridden Stored Property
Swiftui Scrollview Only Scroll in One Direction
Cannot Assign to Value: 'self' Is Immutable
How to Create Generic Convenience Initializer in Swift
Can't Load Images on MAC Screensaver Release Build (It Works on Xcode Debug Build)
Xcode Debugger Displays Incorrect Values for Variables
Get Applicationdidfinishlaunching Call in a View Controller. Parse Not Initialized Yet
Can You Strict Generic Types or Give One Parameter More Than One Type