3 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超10個(gè)贊
編輯/更新:Xcode 10?Swift 4.2
您可以將觀察者添加到視圖控制器中 UIApplication.willResignActiveNotification
NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: UIApplication.willResignActiveNotification, object: nil)
并向您的視圖控制器添加選擇器方法,該方法將在您的應(yīng)用收到該通知時(shí)執(zhí)行:
@objc func willResignActive(_ notification: Notification) {
// code to execute
}

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超6個(gè)贊
在Swift 4和iOS 12中:要觀察應(yīng)用程序進(jìn)入后臺(tái)事件,請(qǐng)將此代碼添加到您的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。如果要觀察應(yīng)用程序是否進(jìn)入前臺(tái)事件,請(qǐng)使用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 關(guān)注
- 987 瀏覽
添加回答
舉報(bào)