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)
在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)
归档时间: |
|
查看次数: |
1222 次 |
最近记录: |