TruMan1
TruMan1

Reputation: 36088

Retrieve application state from background thread?

I'd like to get UIApplication.shared.applicationState from a background thread. If I try to get the application state from a background thread, I get errors when accessing it since it's not the main thread (since it's a UIKit API).

The reason I'm doing this is so I can log events that also includes information such as the current application state. Logging events for me is happening in the background so it does not lock up the main thread.

Is there an alternative for getting the application state within a background thread?

Upvotes: 3

Views: 925

Answers (2)

Kashem
Kashem

Reputation: 125

If someone doesn't want to use notifications. Instead of want to use function or a closure to get the UIApplication.shared.applicationState from any thread. Another solution could be

    func getApplicationCurrentState() ->  UIApplication.State {
        var appCurrentState: UIApplication.State = .inactive
        if Thread.isMainThread {
            appCurrentState = UIApplication.shared.applicationState
        } else {
            DispatchQueue.main.sync {
                appCurrentState = UIApplication.shared.applicationState
            }
        }
        return appCurrentState
    }
    
    func isApplicationInBackGround() -> Bool {
        getApplicationCurrentState() == .background
    }

Upvotes: 0

Alex
Alex

Reputation: 712

Setup notifications for changes to the state on the main thread and assign them atomically to a variable. That variable can now be accessed atomically as well from your background thread.

Upvotes: 4

Related Questions