Is there any way to check if iOS app is in backgro

2019-01-16 08:28发布

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

In:

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

7条回答
The star\"
2楼-- · 2019-01-16 09:03

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.isBackground

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

查看更多
一夜七次
3楼-- · 2019-01-16 09:08

swift 4

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楼-- · 2019-01-16 09:11

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");
}
查看更多
再贱就再见
5楼-- · 2019-01-16 09:12

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]
查看更多
淡お忘
6楼-- · 2019-01-16 09:18

Swift 3

    let state = UIApplication.shared.applicationState
    if state == .background {
        print("App in Background")
    }
查看更多
可以哭但决不认输i
7楼-- · 2019-01-16 09:20

Swift version :

   let state = UIApplication.sharedApplication().applicationState
            if state == .Background {
                print("App in Background")
             }
查看更多
登录 后发表回答