NSNotification in swift

Recently, I was having trouble trying to implement a way to pause and restart the NSTimer in SWIFT. And here is the solution that helped me with the problem. The following code  calls the method when the app is in the background and when the app relaunches

var testEnemy : NSTimer?

override func didMoveToView(view: SKView) {
    /* Setup your scene here */
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("appEnterIntoBackGround:"), name:UIApplicationDidEnterBackgroundNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("appBecomeActive:"), name:UIApplicationWillEnterForegroundNotification, object: nil)

    testEnemy = NSTimer.scheduledTimerWithTimeInterval(1.2,
        target: self,
        selector: "timerUpdate",
        userInfo: nil,
        repeats: true)

Here is the sample method below that is called by the script above.The script helps us manage the NSTimer, however, using SKAction is better for handling action related tasks. For further reference check this linkhttp://stackoverflow.com/questions/23978209/spritekit-creating-a-timer
to learn more about handling NSTimer in spritekit & swift, it will come quite handy.

func timerUpdate() {

func appEnterIntoBackGround(notification : NSNotification) {
    print("App is in Background")
    testEnemy!.invalidate()  //remove timer here when add enter into background.

func appBecomeActive(notification : NSNotification) {

    print("App is active now")
    //add your timer again when app enter into foreground
    testEnemy = NSTimer.scheduledTimerWithTimeInterval(1.2,target: self,selector: "timerUpdate",userInfo: nil,repeats: true) 


Leave a Reply

Your email address will not be published. Required fields are marked *