添加完成处理程序以防止结果“nil”'

时间:2018-02-22 23:51:09

标签: json swift parsing completionhandler

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 {
                let myJson = try JSONSerialization.jsonObject(with: content) as! [String:Any]
                if let rates = myJson["bpi"] as? [String:Any] {
                    if let currency = rates["USD"] as? [String:Any] {
                        if let btc = currency["rate"] as? String {
                            DispatchQueue.main.async{
                                self.bitcoinlabel.text = "$" + btc

                                let btcprice: Double = btc
                            }
                        }
                    }
                }
            }
            catch{
                print(error)
            }
        }
    }
}
task.resume()

如何在viewDidLoad函数中添加一个完整的,以便btcprice将值btc作为值(double)返回而不是nil?

1 个答案:

答案 0 :(得分:0)

正如@rmaddy在评论中建议的那样,您无法更改ViewDidLoad的签名。但是,你可以做的是返回'btcPrice'。

只需创建一个新函数并为其添加闭包。

func btcValue(completion: @escaping((String) -> ())){ //Added Line
    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 {
                    let myJson = try JSONSerialization.jsonObject(with: content) as! [String:Any]
                    if let rates = myJson["bpi"] as? [String:Any] {
                        if let currency = rates["USD"] as? [String:Any] {
                            if let btc = currency["rate"] as? String {
                                DispatchQueue.main.async{
                                    self.bitcoinlabel.text = "$" + btc
                                    completion(btc) //Added Line
                                }
                            }
                        }
                    }
                }
                catch{
                    print(error)
                }
            }
        }
    }
    task.resume()
   }
}

您可以使用这段代码在任何地方调用此函数。

    btcValue { (btc) in
        print(btc)
    }

在此处详细了解闭包:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html