在块中调用时,NSTimer不会触发

时间:2016-04-20 15:03:37

标签: swift nstimer

这有效

 func startTimer () {
    batchTimer = NSTimer.scheduledTimerWithTimeInterval(batchIntervalSeconds, target: self, selector: #selector(Requester.performRemoteRequests), userInfo: nil, repeats: false)

}

这不是

func startTimerInBlock () {
    let urlRequest = NSMutableURLRequest(URL: NSURL(string: "google.com")!, cachePolicy: .ReloadIgnoringLocalCacheData , timeoutInterval: 30)
    urlRequest.HTTPMethod = "GET"
    let session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration())
    let task = session.dataTaskWithRequest(urlRequest) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
        //check there is a response and that it is an http response
        self.batchTimer = NSTimer.scheduledTimerWithTimeInterval(self.batchIntervalSeconds, target: self, selector: #selector(CNVRRequester.performRemoteRequests), userInfo: nil, repeats: false)

    }
    task.resume()
}

有人知道为什么在一个块内调用的计时器不会触发吗?

1 个答案:

答案 0 :(得分:21)

简单修复,将self.startTimer代码放在dispatch_block

 DispatchQueue.main.async {
        self.startTimer()
 }

那应该解决它。

编辑说明

计时器需要一个有效的运行循环。在主线程上初始化时,将自动使用主运行循环。如果要从后台线程运行它,则必须将其附加到该线程运行循环。实施例

DispatchQueue.global(qos: .background).async {
    let timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: selector(fireTimer), repeats: false)
    let runLoop = RunLoop.current
    runLoop.add(timer, forMode: .defaultRunLoopMode)
    runLoop.run()
  }

但是,如果你想确保它只是从主线程运行,只需从一个调度主关闭启动它,它将确保它将运行主线程。

编辑:已更新为Swift 3

编辑2:更新以显示背景计时器答案符合Phil Mitchells的评论