3 回答
TA贡献1802条经验 获得超10个赞
编辑/更新:Xcode 10•Swift 4.2
您可以将观察者添加到视图控制器中 UIApplication.willResignActiveNotification
NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: UIApplication.willResignActiveNotification, object: nil)
并向您的视图控制器添加选择器方法,该方法将在您的应用收到该通知时执行:
@objc func willResignActive(_ notification: Notification) {
// code to execute
}
TA贡献1821条经验 获得超6个赞
在Swift 4和iOS 12中:要观察应用程序进入后台事件,请将此代码添加到您的viewDidLoad()方法中。
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
@objc func appMovedToBackground() {
// do whatever event you want
}
您必须使用UIApplication.didEnterBackgroundNotification。如果要观察应用程序是否进入前台事件,请使用UIApplication.willEnterForegroundNotification
因此,完整的代码将是:
override func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(appCameToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
// Do any additional setup after loading the view.
}
@objc func appMovedToBackground() {
print("app enters background")
}
@objc func appCameToForeground() {
print("app enters foreground")
}
- 3 回答
- 0 关注
- 940 浏览
添加回答
举报