【问题标题】:Use of unresolved identifier when parsing json解析 json 时使用未解析的标识符
【发布时间】:2018-02-22 18:39:53
【问题描述】:
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

                                }
                            }
                        }
                    }
                }
                catch{
                    print(error)
                }
            }
        }
    }
    task.resume()

    let btcprice: Double = btc

问题出在最后一行(使用未解析的标识符“btc”)。如何导出从数据中获取的值,以便在代码块之外或其他函数中使用。

【问题讨论】:

  • btc 仅在 if let btc = 块内可用。

标签: json swift parsing


【解决方案1】:

btc 在外部范围内不可访问。你应该只在它被定义的范围内做任何你想做的事情。

像这样:

if let btc = currency["rate"] as? String {
    DispatchQueue.main.async{
        self.bitcoinlabel.text = "$" + btc
        let btcprice: Double = btc
        // Do Stuff here with btcprice
        // OR Call another func from here like someFunctionWhichUsesTheBtcprice()
        // OR Add CompletionHandler in the Method definition like : completion: @escaping (()->()) and pass the function you want to call after you get the response with the method and call that function here like: completion()
    }
}

此外,如果您将 btcprice 声明为像 var btcprice: Double? 这样的类变量,那么您应该只在该块中分配 self.btcprice = btc。但是无论你想用它做什么,都应该在 API 返回响应之后完成,否则 btcprice 将是 nil

更新代码:

你可以这样使用:

func callAPI(completion: @escaping (Double) -> ()) {
    // Call Your API Here...
    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
                                    if let btcDoubleValue = Double(btc) {
                                        // This will be called when we will get the response and btc value
                                        completion(btcDoubleValue)
                                    }
                                }
                            }
                        }
                    }
                }
                catch{
                    print(error)
                }
            }
        }
    }
    task.resume()
}

这样称呼:

self.callAPI() { (btcprice) in
   // Do your stuff here
}

【讨论】:

  • 好的,谢谢,在声明 btcprice 之前我该怎么做才能等待 API 响应
  • @AleksanderFicek 将完成处理程序添加到您的方法签名
  • @AleksanderFicek 在获得我在更新答案中显示的btcprice 后调用您想要调用的任何函数或执行您想做的事情
  • @AleksanderFicek Chekout 现在更新答案。我添加了更多解释和一些代码,让您了解如何实现您的此类用例。
【解决方案2】:

您可以将其声明为实例变量,但请记住对 API 的调用是异步的,因此在响应返回之前它的值不会是真实的,请在类范围内声明 btc

 var btc: Double?

然后

                if let btc = currency["rate"] as? String {
                            DispatchQueue.main.async{
                                self.bitcoinlabel.text = "$" + btc
                                self.btc = btc 
                            }
                        }

【讨论】:

  • 我将如何等待响应我不断收到错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-25
相关资源
最近更新 更多