Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Tukang Keboen
2,840 PointsCannot invoke 'dataTaskWithRequest' with an argument list of type '(NSURLRequest,(_,_,_),_) throws -> _)
func downloadJSONFromURL(completion: JSONDictionaryCompletion) {
let request: NSURLRequest = NSURLRequest(URL: queryURL)
let dataTask = session.dataTaskWithRequest(request) {
(let data, let response, let error) in
// 1. Check HTTP response for successful GET request
if let httpResponse = response as? NSHTTPURLResponse {
switch(httpResponse.statusCode) {
case 200:
// 2. Create JSON object with data
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject]
completion(jsonDictionary)
default:
print("GET request not successful HTTP status code: \(httpResponse.statusCode)")
}
} else {
print("Error: Not a valid HTTP response")
}
}
dataTask.resume()
}
}
1 Answer
Tori Sambrooks
3,896 Pointsfunc downladJSONfromURL(completion: JSONDictionaryCompletion){
let request: NSURLRequest = NSURLRequest(URL: queryURL)
let dataTask = session.dataTaskWithRequest(request) {
(let data, let response, let error) in
//1. Check HTTP response for succesful GET request
if let httpResponse = response as? NSHTTPURLResponse {
switch(httpResponse.statusCode) {
case 200:
//2. Create JSON object with data
let jsonDictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? [String: AnyObject]
completion(jsonDictionary)
default:
println("GET request not succesful. HTTP status code: \(httpResponse.statusCode)")
}
} else {
println("Error: Not a valid HTTP response")
}
}
dataTask.resume()
}
The mistakes that I as able to identify were that
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject]
should be
let jsonDictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? [String: AnyObject]
and also
print("GET request not successful HTTP status code: (httpResponse.statusCode)")
Should be
println("GET request not succesful. HTTP status code: (httpResponse.statusCode)")
Hope this helps!