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 關注
- 983 瀏覽
添加回答
舉報