我有一个 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
的函数
在该函数中,我有一个打印语句,该打印语句只打印一次,虽然我的计时器应该每 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 是 no response yet
最佳答案
如果您在完成处理程序中有此代码,建议 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 )
关于ios - 为什么 NSTimer 在 swift 中只工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34838414/