Json数据标注

时间:2018-02-10 17:27:47

标签: ios json swift label

我一直在努力解决这个问题,只需要一些关于这个基本问题的快速帮助。

let url = URL(string: "https://api.coindesk.com/v1/bpi/currentprice.json")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
    if error != nil
    {
        print ("Error!")
    }
    else
    {
        if let content = data
        {
            do
            {
                // Array
                let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                if let rates = myJson["bpi"] as? NSDictionary
                {
                    if let currency = rates["USD"] as NSDictionary
                    {
                        if let money = currency["rate"]
                        {
                            print(money)

                        }
                    }
                }
            }
            catch
            {

            }
        }
    }
}
task.resume()

self.label.text = (self.money as String?)

我正在尝试将“money”的数值传递给我的视图控制器中的标签。

1 个答案:

答案 0 :(得分:3)

主要问题是您正在尝试从异步网络请求的完成处理程序外部更新标签。但是,您的代码还有其他几个问题。你不应该在Swift中使用NSDictionary,在解析JSON词典时使用[String:Any].mutableContainers在Swift中也没有任何效果。还要确保将任何与UI相关的更新发送到主线程。

let url = URL(string: "https://api.coindesk.com/v1/bpi/currentprice.json")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
    guard let data = data else {
        print(error!); return
    }
    do {
        if let myJson = try JSONSerialization.jsonObject(with: content) as? [String:Any],
           let rates = myJson["bpi"] as? [String:Any],
           let currency = rates["USD"] as? [String:Any],
           let money = currency["rate"] as? String {
               DispatchQueue.main.async{
                  self.label.text = money
               }
        }
    } catch{
        print(error)
    }
}
task.resume()