Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect when the swift application is foreground from the background?

I want to run a function in my application if the application is not running from the background. How can I do that?

I cannot use applicationDidBecomeActive and applicationDidEnterBackground because I need to detect the situation when it comes from the background, not the state when it is being taken to the background or when it is opened. Also, when the application is opened for the first time, it will not work when it comes from the background.

like image 994
user9413194 Avatar asked Sep 06 '25 03:09

user9413194


1 Answers

Check the current state:

Use UIApplication.shared.applicationState.

switch UIApplication.shared.applicationState {
case .active: // The app is running in the foreground and currently receiving events.
case .inactive: // The app is running in the foreground but is not receiving events. This might happen as a result of an interruption or because the app is transitioning to or from the background.
case .background: // The app is running in the background.
}
like image 101
Mojtaba Hosseini Avatar answered Sep 07 '25 20:09

Mojtaba Hosseini