我有一个http请求,如果我正确收到响应,那么我想启动一个每秒触发一个函数的计时器.该函数也是一个http请求.
这是我启动计时器的代码
if let data = data {
do{
let resultJSON = try NSJSONSerialization.JSONObjectWithData(data,options: [])
requestClient.id = resultJSON["id"] as! Double
self.timerResponse = NSTimer.scheduledTimerWithTimeInterval(1,target: self,selector: "checkIfThereAreResponeses",userInfo: nil,repeats: true)
self.timerResponse!.fire()
}catch{
}
}
如你所见,我正在调用一个名为checkIfThereAreResponses的函数
在该函数中,我有一个print语句,并且该print语句只打印一次,尽管我的计时器应该每1秒工作一次
我有什么遗失?
这就是功能
func checkIfThereAreResponeses(){
if (requestClient!.id != nil) {
let url = NSURL(string: "http://localhost:blablabla")
let request = NSMutableuRLRequest(URL: url)
request.HTTPMethod = "POST"
let session = NSURLSession.sharedSession()
task = session.dataTaskWithRequest(request,completionHandler: {(data,response,error) in
if let error = error {
print("error = \(error)")
}
if let data = data {
do {
let resultJSONArray = try NSJSONSerialization.JSONObjectWithData(data,options: []) as! NSArray
bla bla bla
}catch {
print("no responses yet = \(error)")
}
}
})
task!.resume()
}else {
print("not yet ")
}
}
我收到JUST ONCE的印刷品还没有回复
解决方法
如果你在完成处理程序中有这个代码,建议NSTimer在主线程中运行,这可能是原因.您可能需要以下内容:
dispatch_async(dispatch_get_main_queue(),{
// Your timer logic here
})
Apple文档说:
Timers work in conjunction with run loops. To use a timer effectively,
you should be aware of how run loops operate—see NSRunLoop.
(NSTimer)
The NSRunLoop class is generally not considered to be thread-safe and
its methods should only be called within the context of the current
thread. You should never try to call the methods of an NSRunLoop
object running in a different thread,as doing so might cause
unexpected results.
(NSRunLoop)