ios - 如何为我的长时间运行函数设置超时?

标签 ios swift

我有一些代码可能需要很长时间才能完成的功能。如果它花费的时间超过特定时间,我希望该功能停止继续。我该如何实现?我尝试了以下解决方案,但它并没有停止执行。

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*/
}

最佳答案

试试这个

 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 服务在请求中设置超时的更好方法 set request to 5 seconds timeout

  let urlRequest = NSMutableURLRequest(url: newUrl! as URL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)

        let queue = OperationQueue()

        NSURLConnection.sendAsynchronousRequest(urlRequest as URLRequest, queue: queue)
        {

         }

关于ios - 如何为我的长时间运行函数设置超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48029577/

相关文章:

ios - 通过在 iOS10+ 上打开本地通知来检测应用是否已启动

ios - 我是否必须将 "Login with Apple"作为第一个选项才能让我的 iOS 应用程序获得批准?

c - 将 C 结构函数自动桥接到 Swift 方法

ios - UICollection 的 IndexPath 到底是什么

ios - 在后台模式下定期向服务器发送小数据

iphone - ccTouchesMoved 有效,但 ccTouchMoved 无效

ios - 如何从 UITabBarController 展开到自定义 View

ios - 您可以使用 springs & struts 为不同的设备调整 TableViewCell 的大小吗?

ios - 从 UIViewController 切换到 navigationController 内的其他 ViewController

swift - 在服务器上创建模型的正确方法