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

Joo*_*. P 2 xcode uiviewcontroller ios swift

我的UIViewController类设置如下:

class ViewController: UIViewController {

    var currentTask: NSURLSessionTask?

    ...

}
Run Code Online (Sandbox Code Playgroud)

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

self.currentTask.cancel()
Run Code Online (Sandbox Code Playgroud)

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

func applicationWillResignActive(application: UIApplication) {

}
Run Code Online (Sandbox Code Playgroud)

Joo*_*. P 7

在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
    )
Run Code Online (Sandbox Code Playgroud)

对于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)
Run Code Online (Sandbox Code Playgroud)

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

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

@objc fileprivate func becomeActive() {
    print("== becomeActive ==")
}
Run Code Online (Sandbox Code Playgroud)