有没有办法检查iOS应用程序是否在后台?

dnph8jn4  于 2022-11-19  发布在  iOS
关注(0)|答案(9)|浏览(201)

我想检查应用程序是否在后台运行。
在:

locationManagerDidUpdateLocation {
    if(app is runing in background){
        do this
    }
}
ubby3x7f

ubby3x7f1#

应用程序委派会取得表示状态转换的回呼。您可以据此追踪它。
UIApplication中的applicationState属性也会传回目前的状态。

[[UIApplication sharedApplication] applicationState]
pu82cl6c

pu82cl6c2#

UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground || state == UIApplicationStateInactive)
{
   //Do checking here.
}

这可能有助于您解决问题。
看下面的评论--不活动是一个相当特殊的情况,可能意味着应用程序正在被启动到前台。这可能意味着你的目标是“后台”,也可能不意味着“后台”...

qf9go6mv

qf9go6mv3#

雨燕3

let state = UIApplication.shared.applicationState
    if state == .background {
        print("App in Background")
    }
m1m5dgzv

m1m5dgzv4#

Swift版本:

let state = UIApplication.shared.applicationState
if state == .Background {
    print("App in Background")
}
vyswwuz2

vyswwuz25#

雨燕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
    }
epggiuax

epggiuax6#

如果您更喜欢接收回调而不是“询问”应用程序状态,请在AppDelegate中使用以下两个方法:

- (void)applicationDidBecomeActive:(UIApplication *)application {
    NSLog(@"app is actvie now");
}

- (void)applicationWillResignActive:(UIApplication *)application {
    NSLog(@"app is not actvie now");
}
ippsafx7

ippsafx77#

斯威夫特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
        }
9gm1akwq

9gm1akwq8#

Swift 4.0扩展使访问它更容易:

import UIKit

extension UIApplication {
    var isBackground: Bool {
        return UIApplication.shared.applicationState == .background
    }
}

若要从应用程序中访问:

let myAppIsInBackground = UIApplication.shared.isBackground

如果要查找有关各种状态(activeinactivebackground)的信息,可以找到Apple documentation here

q35jwt9p

q35jwt9p9#

感谢Shakeel Ahmed,这就是我在斯威夫特5中的工作

switch UIApplication.shared.applicationState {
case .active:
    print("App is active")
case .inactive:
    print("App is inactive")
case .background:
    print("App is in background")
default:
    return
}

我希望它能帮助某人=)

相关问题