Search code examples
iosswiftmethodsdelegateswatchkit

Stop method's execution - Swift


When my watchKit app goes to background it fires the delegate method applicationWillResignActive. Method documentation says it can be used to pause ongoing tasks.

I have an ongoing method that i want to be stopped or broken by the use of the external method. How do i do that?

Example

func method1(){
// performing some actions
}

func breakMethod1(){
// running this method can stop (break) the execution of method1
}

Solution

  • This is, of course, assuming that your app has been architected so that breakMethod1() will definitely cancel the action occurring in method1().

    You should set up an observer for an NSNotification at the beginning of method1() like so:

    let notificationCenter = NSNotificationCenter.defaultCenter()
    notificationCenter.addObserver(self, selector: "breakMethod1", name: UIApplicationWillResignActiveNotification, object: nil)
    

    And for the sake of cleanup, you should also remove this observer after it's been triggered like so:

    notificationCenter.removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil)