简体   繁体   English

Swift - JSON函数无法正确更新

[英]Swift - JSON function not updating correctly

I have a JSON function that gets currency exchange data, but the function is only re-sending the JSON request every 28 times. 我有一个获取货币交换数据的JSON函数,但该函数每28次仅重新发送一次JSON请求。 Here is my code: 这是我的代码:

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))
}

The URL does change the price every second, but it is not working when I try to refresh every second of few seconds. URL确实每秒都会改变价格,但是当我尝试每隔几秒钟刷新一次时,它就无法正常工作。 It works when I re-compile my playground just not in the function. 当我重新编译我的游乐场而不是在函数中时,它工作。

Use a timer. 使用计时器。 beginFetch code will perform your fetch every second until you call stopFetch: 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()
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM