Reputation: 3061
Cant seem to get the following code to compile with Xcode 7, I get error "Cannot invoke 'dataTaskWithURL' with an argument list of type"
Looks like completionHandler is no longer optional, cant figure out how to rewrite the following code. Any help appreciated, Thanks
let session = NSURLSession.sharedSession()
let url = NSURL(string: urlString)
var task = session.dataTaskWithURL(url!) {
(data, response, error) -> Void in
if error != nil {
print(error!.localizedDescription)
}
else {
var error: NSError?
var jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSArray
// Do Stuff
}
}
task!.resume()
Upvotes: 1
Views: 11133
Reputation: 377
let url : String = String(format: "http://api.nytimes.com/svc/news/v3/content/nyt/all/720.json?api-key=%@",apiKey)
let url1: NSURL = NSURL(string: url)!
let session = NSURLSession.sharedSession()
let task1 = session.dataTaskWithURL(url1, completionHandler: {
(data, response, error) -> Void in
do {
if data == nil {
return
}
else
{
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary
self.dict = jsonData;
self.array1 = (self.dict.objectForKey("results") as? NSMutableArray)!
dispatch_async(dispatch_get_main_queue()) {
self.table.reloadData()
}
}
} catch {
}
})
Upvotes: 1
Reputation: 21881
As of Swift 2.0 (Xcode 7 beta 6), use dataTaskWithURL()
like this:
var task = session.dataTaskWithURL(url!, completionHandler: {
(data, response, error) -> Void in
:
})
task.resume()
To use NSJSONSerialization.JSONObjectWithData
within the completion handler, you will also need catch errors:
do {
var jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSArray
// Do Stuff
} catch {
// handle error
}
Upvotes: 2
Reputation: 10086
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
Upvotes: 9