我有一个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{
}
}
Run Code Online (Sandbox Code Playgroud)
如你所见,我正在调用一个名为的函数 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 ")
}
}
Run Code Online (Sandbox Code Playgroud)
我接收打印只有一次是no response yet
如果你在完成处理程序中有这个代码,建议NSTimer在主线程中运行,这可能是原因.您可能需要以下内容:
dispatch_async(dispatch_get_main_queue(), {
// Your timer logic here
})
Run Code Online (Sandbox Code Playgroud)
Apple文档说:
定时器与运行循环一起使用.要有效地使用计时器,您应该了解运行循环的运行方式 - 请参阅NSRunLoop.
(NSTimer)
NSRunLoop类通常不被认为是线程安全的,并且只应在当前线程的上下文中调用其方法.您永远不应该尝试调用在不同线程中运行的NSRunLoop对象的方法,因为这样做可能会导致意外结果.
| 归档时间: |
|
| 查看次数: |
864 次 |
| 最近记录: |