我正在尝试从我的数据库中获取数据,但我的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()
}
你知道它为什么不起作用吗?只是为了让你知道一些事情,我不得不使用自从Swift 2开始的do,try,catch,因为它以前工作得很好!
答案 0 :(得分:2)
如果没有完整的错误消息,我们会猜测确切的问题,但您应该ggplot(data=mtcars, aes(x=hp)) + geom_line(aes(fill=..count..), stat="bin", binwidth=10).
对付错误的输入数据:
guard
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()
}
- do
- try
会发现错误,而非异常,因此您必须自己测试有效的网址并有效catch
。此外,避免强制解包可选项(例如NSData
),尤其是当它是合理的运行时错误(例如没有网络)时。改为使用可选的绑定。