Desert Child Desert Child - 3 months ago 30
iOS Question

Invalidating NSTimer

I have 4 NSTimers in my app , that make requests to a rest url every few seconds.

On clicking of a particular button I want to stop the timer so that it stops polling and onclick of another button I want to resume polling.

I have tried invalidate for all timers but does not work.

NOTE: All timers are in different class and I'm trying to invalidate the timers in another class
Any help will be appreciated , thank you.

class NotificationViewController:UIViewController {
var timer:NSTimer?
getEvents(){
if((timer == nil)) {
timer = NSTimer.scheduledTimerWithTimeInterval(20.0, target: self, selector: Selector("getEvents"), userInfo: nil, repeats: true)
}
}
}


In another class I'm doing this on click of a button

class Menu:UIViewController {

@IBAction func buttonTapped(sender: UIButton) {
self.notify.timer?.invalidate()
self.notify.timer = nil
}
}

Answer

Try to create a separate NotificationTimer class and used its shared object all over the project like this way.

class NotificationTimer: NSObject {

    var timer1: NSTimer?
    var timer2: NSTimer?
    var timer3: NSTimer?
    var timer4: NSTimer?

    struct Static {
        static var instance: NotificationTimer?
    }     

    class func sharedManager() -> NotificationTimer {
        if (Static.instance == nil)
        {
            Static.instance = NotificationTimer()
        }
        return Static.instance!
    }

    func getEvents(){
        print("Fired")
        if (timer1 == nil){
            timer1 = NSTimer.scheduledTimerWithTimeInterval(20.0, target: self, selector: Selector("getEvents"), userInfo: nil, repeats: true)
        }
    }    
}

Now call this timer1 object inside any ViewController like this way.

let notificationTimer = NotificationTimer.sharedManager()
notificationTimer.timer1?.invalidate()

Or call that method like this way

NotificationTimer.sharedManager().getEvents()
Comments