Reputation: 119
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.
Upvotes: 4
Views: 6274
Reputation: 746
struct ContentView: View {
@Environment(\.scenePhase) var scenePhase
var body: some View {
Text("Hello, world!")
.padding()
.onChange(of: scenePhase) { newPhase in
if newPhase == .active {
print("Active")
} else if newPhase == .inactive {
print("Inactive")
} else if newPhase == .background {
print("Background")
}
}
}
}
Upvotes: 2
Reputation: 8327
You probably need willEnterForegroundNotification.
Posted shortly before an app leaves the background state on its way to becoming the active app.
Keep in mind thow that this notification posted olso after application(_:didFinishLaunchingWithOptions:)
when opening the application for the first time.
When application opens for the first time the applicationState
is inactive and when the application comes from the background the applicationState
is background.
So, your code will be something like this:
token = NotificationCenter.default.addObserver(
forName: UIApplication.willEnterForegroundNotification,
object: nil,
queue: .main
) { (notification: Notification) in
if UIApplication.shared.applicationState == .background {
// Came from the background
}
}
Upvotes: 4
Reputation: 119128
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.
}
Upvotes: 7