Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access UIViewController's varaibles inside "func applicationWillResignActive"? Swift, iOS xcode

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

}
like image 682
Joon. P Avatar asked Jan 08 '23 00:01

Joon. P


1 Answers

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 ==")
}
like image 173
Joon. P Avatar answered Jan 22 '23 19:01

Joon. P