如何在“func applicationWillResignActive”中访问UIViewController的变量? Swift,iOS xcode

我的UIViewController类设置如下:

class ViewController: UIViewController { var currentTask: NSURLSessionTask? ... } 

如果用户按下Home按钮,我想做

 self.currentTask.cancel() 

但是如何从AppDelegate.swift访问此变量?

 func applicationWillResignActive(application: UIApplication) { } 

在UIViewController类里面的viewDidLoad()中添加

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

对于Swift 4,iOS 11,请使用:

  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) 

最后将这两个函数添加到视图控制器:

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