We can get the application state in iOS through UIApplication.shared.applicationState
and it has to be done from main queue.
So, if we want to create a function that would return an application state or something similar to that, we need to assure two things:
UIApplication
is being accessed from the main queue- Everything is synchronous inside the function
I came up with one approach. I don't know if it's correct or not.
TLDR:
I need to know if the following approach is ok or if there is a better approach than this one to get the application state in iOS. Moreover, is it proper to use Thread.isMainThread
to check whether the execution is being performed on the main queue?
func isInBackground() -> Bool {
var isInBackground = true
// If accessed from main queue, don't need to synchronously get this value through the main queue. Otherwise it would just lock the UI or maybe, crash.
if Thread.isMainThread {
return UIApplication.shared.applicationState == .background
} else {
DispatchQueue.main.sync {
isInBackground = UIApplication.shared.applicationState == .background
}
}
return isInBackground
}