gpt4 book ai didi

ios - Swift - JSON 函数未正确更新

转载 作者:行者123 更新时间:2023-11-28 08:24:38 27 4
gpt4 key购买 nike

我有一个获取货币兑换数据的 JSON 函数,但该函数仅每 28 次重新发送一次 JSON 请求。这是我的代码:

func fetchPrice() {
let url = URL(string: "http://finance.yahoo.com/webservice/v1/symbols/EURUSD=x/quote?format=json")
let data = try? Data(contentsOf: url!)

do {
let object = try! JSONSerialization.jsonObject(with: data!) as? NSDictionary

if let dictionary = object as? [String: AnyObject] {
let title = object?["list"] as! [String:Any]
let title2 = title["resources"] as! [AnyObject]?
let title3 = title2?[0] as! [String:Any]?
let title4 = title3?["resource"] as! [String:Any]?
let fields = title4?["fields"] as! [String:Any]?

let price = fields?["price"] as! String

print(fields?["price"] as! String)
print(fields?["ts"] as! String)
//print(NSDate().timeIntervalSince1970)
//print(dictionary)

}
}
}

while true {
fetchPrice()
sleep(UInt32(1))
}

URL 确实每秒都会更改价格,但是当我尝试每隔几秒刷新一次时它就不起作用了。当我重新编译我的 Playground 而不是在函数中时它起作用了。

最佳答案

使用计时器。 beginFetch 代码将每秒执行一次提取,直到您调用 stopFetch:

    var fetchTimer: Timer!

func beginFetch() {
var fetchCount = 0
fetchTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
fetchCount += 1
print("\n The timer has run \(fetchCount) times")
self.fetchPrice()
}
}

func stopFetch() {
fetchTimer.invalidate()
}

关于ios - Swift - JSON 函数未正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40391544/

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