如何解决有什么方法可以检查iOS应用是否在后台?
| 我想检查应用程序是否在后台运行。 在:locationManagerDidUpdateLocation {
if(app is runing in background){
do this
}
}
解决方法
应用程序委托获取指示状态转换的回调。您可以基于此进行跟踪。
UIApplication中的applicationState属性也返回当前状态。
[[UIApplication sharedApplication] applicationState]
,UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive)
{
//Do checking here.
}
这可以帮助您解决问题。
请参阅下面的评论-非活动状态是一种非常特殊的情况,可能意味着该应用程序正在启动中。根据您的目标,这可能对您意味着“背景”。
,迅捷3
let state = UIApplication.shared.applicationState
if state == .background {
print(\"App in Background\")
}
,迅捷版:
let state = UIApplication.sharedApplication().applicationState
if state == .Background {
print(\"App in Background\")
}
,如果您希望接收回调而不是关于应用程序状态的“询问”,请在AppDelegate
中使用以下两种方法:
- (void)applicationDidBecomeActive:(UIApplication *)application {
NSLog(@\"app is actvie now\");
}
- (void)applicationWillResignActive:(UIApplication *)application {
NSLog(@\"app is not actvie now\");
}
,迅捷5
let state = UIApplication.shared.applicationState
if state == .background {
print(\"App in Background\")
//MARK: - if you want to perform come action when app in background this will execute
//Handel you code here
}
else if state == .foreground{
//MARK: - if you want to perform come action when app in foreground this will execute
//Handel you code here
}
,迅捷4+
let appstate = UIApplication.shared.applicationState
switch appstate {
case .active:
print(\"the app is in active state\")
case .background:
print(\"the app is in background state\")
case .inactive:
print(\"the app is in inactive state\")
default:
print(\"the default state\")
break
}
,一个Swift 4.0扩展,使访问起来更加容易:
import UIKit
extension UIApplication {
var isBackground: Bool {
return UIApplication.shared.applicationState == .background
}
}
要从您的应用内访问:
let myAppIsInBackground = UIApplication.shared.isBackground
如果要查找有关各种状态(active
,inactive
和background
)的信息,请在此处找到Apple文档。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。