4

I have my UIViewController class set up like this :

class ViewController: UIViewController {

    var currentTask: NSURLSessionTask?

    ...

}

If the user presses Home button, I want to do

self.currentTask.cancel()

But how can I access this variable from AppDelegate.swift?

func applicationWillResignActive(application: UIApplication) {

}
Joon. P
  • 2,238
  • 7
  • 26
  • 53

2 Answers2

9

in viewDidLoad() inside UIViewController class, add

    // Add UIApplicationWillResignActiveNotification observer
    NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: "resigningActive",
        name: UIApplicationWillResignActiveNotification,
        object: nil
    )
    NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: "becomeActive",
        name: UIApplicationDidBecomeActiveNotification,
        object: nil
    )

for Swift 4, iOS 11, use this:

 NotificationCenter.default.addObserver(
    self, 
    selector: #selector(ViewController.resigningActive), 
    name: NSNotification.Name.UIApplicationWillResignActive, 
    object: nil)

 NotificationCenter.default.addObserver(
    self, 
    selector: #selector(ViewController.becomeActive), 
    name: NSNotification.Name.UIApplicationDidBecomeActive, 
    object: nil)

Finally add these two functions to your view controller:

@objc fileprivate func resigningActive() {
    print("== resigningActive ==")
}

@objc fileprivate func becomeActive() {
    print("== becomeActive ==")
}
John Pavley
  • 5,366
  • 2
  • 14
  • 16
Joon. P
  • 2,238
  • 7
  • 26
  • 53
0

For swift 4 and above you can use

UIApplication.willResignActiveNotification

and

UIApplication.didBecomeActiveNotification

for notification name.

Mayur Karmur
  • 2,119
  • 14
  • 35