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) {
}
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 ==")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With