加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:53:18 所属栏目:百科 来源:网络整理
导读:这有效 func startTimer () { batchTimer = NSTimer.scheduledTimerWithTimeInterval(batchIntervalSeconds,target: self,selector: #selector(Requester.performRemoteRequests),userInfo: nil,repeats: false)} 事实并非如此 func startTimerInBlock () {
这有效

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,selector: #selector(CNVRRequester.performRemoteRequests),repeats: false)

    }
    task.resume()
}

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

解决方法

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

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

那应该解决它.

编辑说明

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

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

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

编辑:已更新为Swift 3

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读