why NSTimer works just once in swift

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 {
            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)

as you see, I'm calling a function called checkIfThereAreResponses

In that function, i have a print statement, and that print statement is being printed just once, though my timer supposed to work each 1 second

what missing i have?

And this is the function

 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)")
    }else {
        print("not yet ")

the print that i receive JUST ONCE is the 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.


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.


An NSTimer works by being scheduled on a runloop. If you call this method in the completionHandler of the session, it will be scheduled to the runloop of the thread that that completionHandler is currently running on. As this thread is not owned by you, but by the system, it will be disposed of by the system. This might be immediately after the completionHandler is done executing, or it might be much later. With the thread, the runloop is gone too, thus, your timer might fire never, a couple of times or just once; there is no telling really as it depends on when the system will remove the thread.

Therefore, you should create the timer on a thread you own, or, easier, dispatch the creation of the timer to the main thread (dispatch_get_main_queue() is your friend). Another option is to create an NSTimer with one of the +timerWithTimeInterval... methods and then add it to the main runloop using [NSRunloop mainRunloop] addTimer: yourTimer forMode NSRunLoopCommonModes]. Remember that the timer will call your selector on the same thread as the the runloop it runs on.

As a side note, polling a server might not be the best way to go on a mobile device. If you control the server, it might be better to send a push notification to the device when there is new data for it. This will save battery on the device, and reduce the load on your server. However, if you do not control the server, it would be more complicated to achieve this, and then polling might be a good compromise.

Need Your Help

debugging c programs

c debugging

Programming in a sense is easy. But bugs are something which always makes more trouble. Can anyone help me with good debugging tricks and softwares in c?