Is there any way to check if iOS app is in background?

后端 未结 8 831
滥情空心
滥情空心 2020-12-04 10:38

I want to check if the app is running in the background.

In:

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


        
相关标签:
8条回答
  • 2020-12-04 10:54

    App delegate gets callbacks indicating state transitions. You can track it based on that.

    Also the applicationState property in UIApplication returns the current state.

    [[UIApplication sharedApplication] applicationState]
    
    0 讨论(0)
  • 2020-12-04 10:54

    Swift 3

        let state = UIApplication.shared.applicationState
        if state == .background {
            print("App in Background")
        }
    
    0 讨论(0)
  • 2020-12-04 10:54

    If you prefer to receive callbacks instead of "ask" about the application state, use these two methods in your AppDelegate:

    - (void)applicationDidBecomeActive:(UIApplication *)application {
        NSLog(@"app is actvie now");
    }
    
    
    - (void)applicationWillResignActive:(UIApplication *)application {
        NSLog(@"app is not actvie now");
    }
    
    0 讨论(0)
  • 2020-12-04 11:01

    Swift 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
            }
    
    0 讨论(0)
  • 2020-12-04 11:04

    A Swift 4.0 extension to make accessing it a bit easier:

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

    To access from within your app:

    let myAppIsInBackground = UIApplication.shared.isBackground
    

    If you are looking for information on the various states (active, inactive and background), you can find the Apple documentation here.

    0 讨论(0)
  • 2020-12-04 11:06

    swift 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
        }
    
    0 讨论(0)
提交回复
热议问题