我有一个带有一些代码的函数,可能需要很长时间才能完成。如果该功能花费的时间超过特定时间,我希望该功能停止继续。我怎样才能实现这个?我尝试了下面的解决方案,但它不会停止执行。
override func viewDidLoad() {
super.viewDidLoad()
let task = DispatchWorkItem {
self.myfunction()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0, execute: {
task.cancel()
})
task.perform()
}
func myfunction() -> Void {
/*some codes that may take long time to complete*/
}
Try this
var stop:Bool!
override func viewDidLoad() {
super.viewDidLoad()
stop = false
let task = DispatchWorkItem {
self.myfunction()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0, execute: {
stop = true
})
task.perform()
}
func myfunction() -> Void {
if(stop)
{
// invalidate timer , break for loop or return
}
}
// Web 服务在请求中设置超时的更好方法此处将请求设置为 5 秒超时
let urlRequest = NSMutableURLRequest(url: newUrl! as URL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
let queue = OperationQueue()
NSURLConnection.sendAsynchronousRequest(urlRequest as URLRequest, queue: queue)
{
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)