【问题标题】:How to send HTTP Request at intervals and Asynchronously如何以间隔和异步方式发送 HTTP 请求
【发布时间】:2017-05-15 09:16:25
【问题描述】:

我有一个带有 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)
  }
}

我怎样才能使用本机 swift 代码以间隔和异步方式执行 HTTP 请求?

提前谢谢你。

【问题讨论】:

    标签: ios swift asynchronous dynamic httprequest


    【解决方案1】:

    我终于使用了 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()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-01
      • 2013-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多