I have a http request, and if I receive the response correctly, then I want to start a timer that fires a function each second. That function is also a http request.
this is my code to fire the timer
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
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 ")
}
}
no response yet
If you have this code in completion handler, it is recommended NSTimer is running in the main thread so this could be the reason. You might need something like:
dispatch_async(dispatch_get_main_queue(), {
// Your timer logic here
})
Apple docs say:
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.