在 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 ==")
}