线程1:exc_bad_instruction(code = exc_i386_invop,subcode = 0x0)错误

时间:2016-02-03 23:36:26

标签: ios swift exception optional

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


}
@IBAction func onbutton(sender: UIButton) {

    inputarea.text = "Success"
    getweatherdata("http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98")

    // UIApplication.sharedApplication().openURL(NSURL(string:"http://www.reddit.com/")!)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func getweatherdata(urlString : String){

    let url = NSURL(string: urlString)
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in dispatch_async(dispatch_get_main_queue(),{
        self.setLabels(data!)
        })
    }
    task.resume()
}

我正在尝试实现一个简单的天气应用程序,我能够编译代码,但一旦执行后我面临错误“线程1:exc_bad_instruction(代码= exc_i386_invop,子代码= 0x0)错误”在函数调用自我.setLabels(数据!),我检查了网址,它返回的数据不是零。

我有功能setLabels提取子数据并显示它,如果有人需要它我会很高兴提供整个代码。谢谢

请查看以下setLabels函数,appname和templ是视图中的标签

        func setLabels(weatherdata: NSData){
        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(weatherdata, options: []) as? NSDictionary {
                print(jsonResult)

                if let name = jsonResult["name"] as? String{
                    appname.text = name
                }

                if let main = jsonResult["main"] as? String{
                    //if let temp = main["temp"] as? Double {
                    //templ.text = String(format: "%.1f",temp)
                    templ.text = main

                }
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }

2 个答案:

答案 0 :(得分:0)

可能是您不正确地展开了JSON数据。如果输入错误,则在打开时可能会找到nil。您是否正在使用if to解析您的JSON或某种JSON解析器?你介意发布完整的setLabels()函数吗?

答案 1 :(得分:0)

我找到了解决方案,因为我试图通过http / https获取数据,它会打开漏洞并抛出此安全异常,因此我在处理它的info.plist文件中添加了以下行,

    <key>NSAppTransportSecurity</key><dict><key>NSAllowsArbitraryLoads</key><true/></dict>