目前,我正在同步非隔离上下文中调用主要参与者隔离实例方法“openURL”;这是 Swift 6 中的错误,在 self.openURL(url) 中出现警告,您知道吗......
目前,我得到
Call to main actor-isolated instance method 'openURL' in a synchronous nonisolated context; this is an error in Swift 6
警告
self.openURL(url)
您知道我该如何解决此问题吗?以下是代码片段。
谢谢。
@MainActor
private func shareAndBye(url: String) {
self.extensionContext?.completeRequest(returningItems: nil, completionHandler: { _ in
if let encodedURL = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
let appURL = "melonote://share?url=" + encodedURL
guard let url = URL(string: appURL) else { return }
_ = self.openURL(url)
}
})
}
// Courtesy: https://.com/a/44499222/13363449
// Function must be named exactly like this so a selector can be found by the compiler!
// Anyway - it's another selector in another instance that would be "performed" instead.
@objc private func openURL(_ url: URL) -> Bool {
var responder: UIResponder? = self
while responder != nil {
if let application = responder as? UIApplication {
return application.perform(#selector(openURL(_:)), with: url) != nil
}
responder = responder?.next
}
return false
}
如果你感兴趣的话,这里有完整的代码片段
https://gist.github.com/yccheok/cf7358a2f8a813da290ab36240f81c52
谢谢。
我将桥 completeRequest
使用延续来 async
实现 async
,完成处理程序中的代码可以跳回到主参与者。
在视图控制器中添加这样的方法,
@discardableResult
private func completeRequestAsync(returningItems items: [Any]?) async -> Bool? {
guard let extensionContext else { return nil }
return await withCheckedContinuation { continuation in
extensionContext.completeRequest(returningItems: items) {
continuation.resume(returning: $0)
}
}
}
然后也进行 shareAndBye
这样的操作 async
,这样就可以调用上面的方法了。
private func shareAndBye(url: String) async {
await completeRequestAsync(returningItems: nil)
if let encodedURL = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
let appURL = "melonote://share?url=" + encodedURL
guard let url = URL(string: appURL) else { return }
_ = self.openURL(url)
}
}
从要点来看,您似乎已经 shareAndBye
从 a Task { ... }
,因此您只需要在呼叫中添加单词就 await
可以了。