I'm trying to fetch data from my db but I have an exc_bad_instruction on my NSJSONSerialization.
func request(url:String, callback:(NSDictionary) -> ()){
let nsURL = NSURL(string: url)
let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!){
(data, response, error) in
//var error:NSError?
var response:NSDictionary
do{
response = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
callback(response)
}catch{
print("Something went wrong!")
}
}
task.resume()
}
Do you have any idea on why it's not working? Just to let you know something, I had to use the do, try, catch since Swift 2 because it was working great before!
Without the full error message we're guessing regarding the precise problem, but you should guard
against bad input data:
func request(url:String, callback:(NSDictionary) -> ()){
let nsURL = NSURL(string: url)
guard nsURL != nil else {
print("URL not valid: \(url)")
return
}
let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!){
(data, response, error) in
guard data != nil else {
print("dataTaskWithURL failed: \(error)")
return
}
do {
if let response = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
callback(response)
} else {
print("JSON parsing succeeded, but cast to dictionary failed")
}
} catch let parseError {
print("Something went wrong: \(parseError)")
}
}
task.resume()
}
The do
-try
-catch
catches errors, not exceptions, so you have to test for valid URL and valid NSData
yourself. Also, avoid forced unwrapping of optionals (e.g. !
), especially when it is a plausible runtime error (e.g. no network). Use optional binding instead.