gpt4 book ai didi

ios - 分派(dispatch)到主线程时返回值

转载 作者:搜寻专家 更新时间:2023-11-01 05:54:59 29 4
gpt4 key购买 nike

我有一个从后台线程调用的函数 func getValue() -> Bool。这是有意的,也是必须的。现在,getValue() 需要在主线程上执行一些操作,在这种情况下它需要访问 UIApplication.shared.canOpenURL,它必须在主队列上运行.

这是我当前的功能:

func getValue() -> Bool {
guard let url = URL(string: "someurl") else { return false }
return UIApplication.shared.canOpenURL(url)
}

我如何将该函数转换为线程安全函数,即确保它始终在主线程上运行,而无需

  • 从主线程开始调用函数
  • 重构函数以在闭包中返回值

我已经试过了:

// 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
}

还有这个:

// 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)
}
}

但它们都不起作用。有什么想法吗?

最佳答案

你正在寻找一个信号量 - 试试这个:

DispatchQueue.global(qos: .background).async {
var value: Bool? = nil
let semaphore = DispatchSemaphore(value: 0)
DispatchQueue.main.async {
let alert = UIAlertController(title: "Choose one", message: "Take your time, I'll wait", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "true", style: .default, handler: { _ in
value = true
semaphore.signal()
}))
alert.addAction(UIAlertAction(title: "false", style: .default, handler: { _ in
value = false
semaphore.signal()
}))
self.present(alert, animated: true, completion: nil)
}
semaphore.wait()
print("Choice: \(value!)")
}

或者使用上面的示例:

func getValue() -> Bool {
var flag = false
let semaphore = DispatchSemaphore(value: 0)

DispatchQueue.main.async {
if let url = URL(string: "someurl"), UIApplication.shared.canOpenURL(url) {
flag = true
semaphore.signal()
}
}
semaphore.wait()
return flag
}

关于ios - 分派(dispatch)到主线程时返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51909509/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com