gpt4 book ai didi

ios - 如何间隔和异步发送HTTP请求

转载 作者:行者123 更新时间:2023-11-30 12:27:39 27 4
gpt4 key购买 nike

我有一个带有 webview 和 uiview 的应用程序,显示动态内容。所以我必须保持 uiview 内容通过网络服务器动态刷新。我是 swift 新手,所以我从单个 webview 构建了这个应用程序,并且最近添加了 uiview。

现在我使用下面的愚蠢代码来保持 uiview 内容同步。使用js异步进行http请求,同时调用swift代码。

js代码,

$interval(function()
{
$http.get("http://192.168.1.66/uidata")
.success(function(response)
{
window.webkit.messageHandlers.startLive.postMessage(response.data);
}
}, 3000);

快速代码,

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if(message.name == "startLive") {
startLive(message.body)
}
}

如何使用 native swift 代码定期异步执行 HTTP 请求?

提前谢谢您。

最佳答案

我最终使用了异步的 Timer 和 URLSession 来实现它。

var timer: Timer?

func startTimer() {

if timer == nil {
timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(self.loop), userInfo: nil, repeats: true)
}
}

func stopTimer() {
if timer != nil {
timer?.invalidate()
timer = nil
}
}

func loop() {
let liveInfoUrl = URL(string: "http://192.168.1.66/api/cloud/app/liveInfo/7777")
let task = URLSession.shared.dataTask(with: liveInfoUrl! as URL) {data, response, error in
guard let data = data, error == nil else { return }
print(String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) ?? "aaaa")
}
task.resume()
}

关于ios - 如何间隔和异步发送HTTP请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43975593/

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