【发布时间】:2015-10-26 01:49:51
【问题描述】:
我正在尝试从我的数据库中获取数据,但我的 NSJSONSerialization 上有一个 exc_bad_instruction。
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, try, catch 从 Swift 2 开始,因为它以前工作得很好!
【问题讨论】:
-
您确定 JSON 中最外层的对象是字典吗?
-
顺便说一句,我鼓励您将该回调参数更改为可选,然后确保即使您有错误也调用回调(为字典传递
nil)。出现错误(尤其是应用程序无法控制的运行时错误,例如网络或服务器问题)将非常令人沮丧,但调用者却没有被告知这种情况。请注意,Apple 的完成处理程序始终具有可选参数(并且还包括NSError对象,以便您知道错误是什么):我建议您对完成块执行相同的操作。
标签: ios iphone swift nsjsonserialization xcode7-beta4