I have a function func getValue() -> Bool
that's called from a background thread. This is intentional and also required. Now, the getValue()
needs to execute something on the main thread, in this case it needs to access UIApplication.shared.canOpenURL
, which must be run on the main queue.
This is my current function:
func getValue() -> Bool {
guard let url = URL(string: "someurl") else { return false }
return UIApplication.shared.canOpenURL(url)
}
How can I convert that function to a thread safe one, namely to make sure it always runs on the main thread, without
- calling the function from the main thread to begin with
- refactoring the function to return the value in a closure
I've tried this:
// This causes a deadlock, see https://stackoverflow.com/a/42484670/1531270
func getValue() -> Bool {
var flag = false
let group = DispatchGroup()
group.enter()
DispatchQueue.main.async {
if let url = URL(string: "someurl"), UIApplication.shared.canOpenURL(url) {
flag = true
}
group.leave()
}
group.wait()
return flag
}
and this:
// This crashes with EXC_BREAKPOINT (SIGTRAP) dispatch_sync called on queue already owned by current thread
func getValue() -> Bool {
return DispatchQueue.main.sync {
guard let url = URL(string: "someurl") else { return false }
return UIApplication.shared.canOpenURL(url)
}
}
but neither of them works. Any ideas?