gpt4 book ai didi

json - 添加完成处理程序以防止结果 'nil'

转载 作者:行者123 更新时间:2023-11-28 15:00:48 25 4
gpt4 key购买 nike

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 函数添加一个 complete,以便 btcprice 返回值 btc 作为值( double )而不是 nil?

最佳答案

正如@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

关于json - 添加完成处理程序以防止结果 'nil',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48939098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com