预制件内部封闭

时间:2018-04-04 22:16:38

标签: ios swift uiviewcontroller closures completionhandler

我试图在一个单独的视图控制器中显示btc的值,但如果我在闭包内设置标签等于btc,则EthViewController不会改变。

 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 {

                                    completion(btc) //Added Line
                            }
                        }
                    }
                }
                catch{
                    print(error)
                }
            }
        }
    }
    task.resume()
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let EthViewController = segue.destination as! EthViewController

    btcValue { (btc) in
        print(btc)
        EthViewController.ethprice_string = btc
        }
    }

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    performSegue(withIdentifier: "segue_eth", sender: self)
}

无论如何我可以从闭包内部预先形成一个segue或者在闭包之外返回值btc吗?非常感谢任何帮助。

0 个答案:

没有答案