检测iOS应用程序进入后台

Joh*_*ood 22 iphone ios swift

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

Leo*_*bus 46

编辑/更新:Xcode 10•Swift 4.2

您可以将观察者添加到视图控制器中 UIApplication.willResignActiveNotification

NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: UIApplication.willResignActiveNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)

并向您的视图控制器添加一个选择器方法,该方法将在您的应用收到该通知时执行:

@objc func willResignActive(_ notification: Notification) {
    // code to execute
}
Run Code Online (Sandbox Code Playgroud)


dim*_*mdy 7

Swift3

let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: Notification.Name.UIApplicationWillResignActive, object: nil)


func appMovedToBackground() {
    print("App moved to background!")
}
Run Code Online (Sandbox Code Playgroud)

  • 应该注意的是,这不再适用于 iOS 13 下的应用程序,除非该应用程序选择不使用场景。 (2认同)

小智 7

用户界面

从背景

Text("Hello, World!")
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
    print("To the foreground!")
}
Run Code Online (Sandbox Code Playgroud)

到背景

Text("Hello, World!")
    .onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
        print("To the background!")
    }
Run Code Online (Sandbox Code Playgroud)


Sur*_*raj 6

要检测应用程序是否进入后台,您可以在appDelegate.m中查找应用程序委托方法

applicationDidEnterBackground

一旦应用程序进入后台,就会调用此方法.


mum*_*umu 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
    }
Run Code Online (Sandbox Code Playgroud)

您必须使用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")
}
Run Code Online (Sandbox Code Playgroud)