【问题标题】:thread 1: exc_bad_instruction(code=exc_i386_invop,subcode=0x0) error线程 1: exc_bad_instruction(code=exc_i386_invop,subcode=0x0) 错误
【发布时间】:2016-05-13 09:45:04
【问题描述】:
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()
}

我正在尝试实现一个简单的天气应用程序,我能够编译代码,但一旦执行后,我在函数调用 self 处遇到错误“线程 1:exc_bad_instruction(code=exc_i386_invop,subcode=0x0) 错误” .setLabels(data!),我检查了 url,它返回的数据不是 nil。

我有函数 setLabels 提取儿子数据并显示它,如果有人需要,我很乐意提供整个代码。谢谢

请找到下面的 setLabels 函数,appname 和 templ 是 View 中的标签

        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)
        }

【问题讨论】:

    标签: ios swift exception optional


    【解决方案1】:

    可能是您未正确解开 JSON 数据。如果某些内容输入错误,则在展开时可能会发现 nil。您是在使用 if let 来解析您的 JSON,还是使用某种 JSON 解析器?您介意发布完整的 setLabels() 函数吗?

    【讨论】:

    • 我已经添加了代码,请您看一下,谢谢
    【解决方案2】:

    我找到了解决方案,当我试图通过 http/https 获取数据时,它打开了一个漏洞并引发了这个安全异常,所以我在处理它的 info.plist 文件中添加了以下行,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-19
      • 2016-12-06
      • 1970-01-01
      • 2015-05-02
      • 2021-11-03
      相关资源
      最近更新 更多