猿问

检测iOS应用进入后台

我正在为Swift编写的iOS游戏。我试图找到一种方法来检测应用程序何时进入后台模式或由于其他原因而中断,例如电话,但找不到任何东西。我该怎么做?



拉丁的传说
浏览 946回答 3
3回答

守候你守候我

编辑/更新:Xcode 10•Swift 4.2您可以将观察者添加到视图控制器中 UIApplication.willResignActiveNotificationNotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: UIApplication.willResignActiveNotification, object: nil)并向您的视图控制器添加选择器方法,该方法将在您的应用收到该通知时执行:@objc func willResignActive(_ notification: Notification) {    // code to execute}

达令说

在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")}
随时随地看视频慕课网APP
我要回答