【发布时间】:2016-12-22 15:46:17
【问题描述】:
如果我的应用程序处于后台模式或前台,有什么方法可以知道它的状态。谢谢
【问题讨论】:
-
不知道具体情况,但是当应用程序在 appDelegate 中的
func applicationDidEnterBackground(application: UIApplication) { }进入后台时,您会接到电话
标签: ios iphone swift swift3 lifecycle
如果我的应用程序处于后台模式或前台,有什么方法可以知道它的状态。谢谢
【问题讨论】:
func applicationDidEnterBackground(application: UIApplication) { } 进入后台时,您会接到电话
标签: ios iphone swift swift3 lifecycle
[UIApplication sharedApplication].applicationState 将返回应用程序的当前状态,例如:
或者如果您想通过通知访问,请参阅UIApplicationDidBecomeActiveNotification
Swift 3+
let state = UIApplication.shared.applicationState
if state == .background || state == .inactive {
// background
} else if state == .active {
// foreground
}
switch UIApplication.shared.applicationState {
case .background, .inactive:
// background
case .active:
// foreground
default:
break
}
目标 C
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive) {
// background
} else if (state == UIApplicationStateActive) {
// foreground
}
【讨论】:
斯威夫特 3
let state: UIApplicationState = UIApplication.shared.applicationState
if state == .background {
// background
}
else if state == .active {
// foreground
}
【讨论】:
斯威夫特 4
let state = UIApplication.shared.applicationState
if state == .background {
print("App in Background")
}else if state == .active {
print("App in Foreground or Active")
}
【讨论】:
如果有人想要在 swift 3.0 中使用它
switch application.applicationState {
case .active:
//app is currently active, can update badges count here
break
case .inactive:
//app is transitioning from background to foreground (user taps notification), do what you need when user taps here
break
case .background:
//app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here
break
default:
break
}
适用于 Swift 4
switch UIApplication.shared.applicationState {
case .active:
//app is currently active, can update badges count here
break
case .inactive:
//app is transitioning from background to foreground (user taps notification), do what you need when user taps here
break
case .background:
//app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here
break
default:
break
}
【讨论】:
在您的UIViewController 中的viewDidload 中使用这些观察者:
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
nc.addObserver(self, selector: #selector(appMovedToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
和方法:
@objc func appMovedToBackground() {
}
@objc func appMovedToForeground() {
}
【讨论】:
您可以在应用程序进入后台或进入前台时添加一个布尔值。 您可以使用 App 委托获得此信息。
根据 Apple 文档,也许您还可以使用应用程序的 mainWindow 属性或应用程序的活动状态属性。
讨论 当应用程序的故事板或 nib 文件尚未完成加载时,此属性中的值为 nil。当应用处于非活动或隐藏状态时,它也可能为 nil。
【讨论】: