ios - 为什么 NSTimer 在 swift 中只工作一次

标签 ios swift

我有一个 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 ONCEno 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/

相关文章:

ios - 我们是否需要为所有 iPhone/iPad 设备提供单独的 Storyboard?

ios - 当另一个按钮被隐藏时居中一个按钮的约束

ios - 问题 TextField 更改为搜索文本

ios - UIDevice currentDevice 模型可能的值

swift - ARC(自动引用计数)实战

ios - 使用 NSURLConnection 连续发送 100 多个请求并在发送下一个请求之前等待每个响应

ios - 使用枚举时实现 NSObject 协议(protocol)时出现链接器错误?

swift - 是否可以将 NSData(从 NSKeyedArchiver 获得)保存为 NSString,然后作为 NSData 读回?

ios - 为什么在 iOS 上使用 UserDefaults 存储敏感信息不安全?

ios - 为什么我的自定义 UITextField 在 Interface Builder 中与在设备上运行时看起来不同?