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

标签 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 确实每秒都会更改价格,但是当我尝试每隔几秒刷新一次时它就不起作用了。当我重新编译我的 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/

相关文章:

ios - 将文本绘制到 UIView,但 CATextLayer 不起作用

ios - 自定义按钮标题在 iPad 上不可见

ios - Google Analytics for iOS v3 的 kGAIScreenName 未声明?

ios - Firebase 快速作为 OS X 的后端服务

swift - 如何在SwiftUi中创建多行TextField?喜欢记事应用?

ios - 使用未声明的标识符核心数据

javascript - Youtube 数据 API 视频嵌入限制

android - 如何为 Gson 的 TypeToken 添加泛型类型?

javascript - 无法访问 JSON 属性 - "Cannot read property of undefined"

swift - UIAlertController 不会把后台的所有元素都转成B/W