【问题标题】:exc_bad_instruction on NSJSONSerializationNSJSONSerialization 上的 exc_bad_instruction
【发布时间】: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


【解决方案1】:

没有完整的错误消息,我们猜测确切的问题,但您应该 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 捕获错误,而不是异常,因此您必须自己测试有效的 URL 和有效的 NSData。此外,避免强制解包选项(例如!),尤其是当它是一个合理的运行时错误(例如没有网络)时。请改用可选绑定。

【讨论】:

  • 感谢您的回答,代码现在运行,但没有显示我的数据,根据控制台,看来连接有问题:/ 我会看看!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2016-01-09
  • 1970-01-01
  • 1970-01-01
  • 2019-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-10
相关资源
最近更新 更多