这有效
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。