我正在研究用Swift编写的iOS游戏。我试图找到一种方法来检测应用程序何时进入后台模式或因其他原因而中断,例如电话但无法找到任何内容。我该怎么做?
答案 0 :(得分:41)
编辑/更新: 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
}
答案 1 :(得分: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!")
}
答案 2 :(得分:6)
要检测应用进入后台,您可以登录appDelegate.m 找到应用程序委托方法
applicationDidEnterBackground
一旦应用程序进入后台,就会调用此方法。
答案 3 :(得分:6)
SwiftUI
从后台
Text("Hello, World!")
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
print("To the foreground!")
}
到背景
Text("Hello, World!")
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
print("To the background!")
}
答案 4 :(得分:2)
在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")
}
答案 5 :(得分:1)
查看UIApplicationDeletegate
实例中定义的委托方法(默认情况下称为AppDelegate.m
)。具体来说,以下内容非常有用:
- (void)applicationWillResignActive:(UIApplication *)application
调用此方法可让您的应用知道它即将从活动状态转为非活动状态。对于某些类型的临时中断(例如来电或SMS消息)或当用户退出应用程序并且它开始转换到后台状态时,可能会发生这种情况。处于非活动状态的应用程序继续运行,但不会将传入事件分派给响应者。
取自Apple文档 - here
答案 6 :(得分:0)
对于 SwiftUI,您可以使用:
YourView()
.onReceive(NotificationCenter.default.publisher(for: UIScene.willDeactivateNotification)) { _ in
//...
}