Swift - JSON函数无法正确更新

时间:2016-11-02 23:34:11

标签: ios json swift

我有一个获取货币兑换数据的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确实每秒都会改变价格,但是当我尝试每隔几秒钟刷新一次时,它就无法正常工作。当我重新编译我的游乐场而不是在函数中时,它可以工作。

1 个答案:

答案 0 :(得分:0)

使用计时器。 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()
    }