我需要做一个关于这段代码的循环到无限时间的后台线程 [英] I need to do an background threads with loop to infinity time about this code

查看:126
本文介绍了我需要做一个关于这段代码的循环到无限时间的后台线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要做一个关于这段代码的循环到无限时间的后台线程。
如果有可能我需要睡一个大约15秒。

I need to do an background threads with loop to infinity time about this code. if it's possible I need to have an sleep about 15 seconds.

代码是:

let request = NSMutableURLRequest(url: NSURL(string: "my url string")! as URL)
request.httpMethod = "POST"
let postString = "my post string"
request.httpBody = postString.data(using: String.Encoding.utf8)

let task = URLSession.shared.dataTask(with: request as URLRequest) {
    data, response, error in
    if error != nil {
        print("error=\(String(describing: error))")
        return
    }
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
    print("responseString = \(String(describing: responseString))")
}
task.resume()


推荐答案

作为David S在他的评论中说,你无法在iOS的后台无限期地运行任务。您可以询问后台时间,然后大约需要3分钟。

As David S says in his comment, you can't run tasks indefinitely in the background in iOS. You can ask for background time, and then you get about 3 minutes.

URLSession支持操作系统级别的文件后台下载,但它不会执行 POST ,它不会经常轮询服务器 GET 。简而言之,我认为你在iOS上运气不好。

URLSession has OS level support for background downloading of files, but it won't do a POST, and it won't poll the server that frequently for a GET. In short I think you're out of luck on iOS.

(为了保持电池续航时间,苹果公司不断努力使应用程序不断运行。用户手机被锁定的时间,CPU进入功耗非常低的模式。)

(Apple goes to great length to keep apps from running constantly in order to preserve battery life. Most of the time the user's phone is locked and the CPU goes to a very low power mode.)

这篇关于我需要做一个关于这段代码的循环到无限时间的后台线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆