达令说
在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")}