0

await UIApplication.shared.open(settingsURL)在 Swift 内部调用,Task但收到 Xcode 运行时警告:

UIApplication.open(_:options:completionHandler:) 只能在主线程中使用

Task {
    guard let settingsURL = await URL(string: UIApplication.openSettingsURLString) else {
        return
    }
    await UIApplication.shared.open(settingsURL) // <-- runtime warning when called
}

SDK 显示了这些方法:

@available(iOS 10.0, *)
open func open(_ url: URL, options: [UIApplication.OpenExternalURLOptionsKey : Any] = [:], completionHandler completion: ((Bool) -> Void)? = nil)

@available(iOS 10.0, *)
open func open(_ url: URL, options: [UIApplication.OpenExternalURLOptionsKey : Any] = [:]) async -> Bool

错误消息暗示它认为我正在使用第一个非异步的(因为提到了完成处理程序),但我不是。UIApplication被标记,MainActor所以我的理解是通过实例调用的所有内容都UIApplication自动在主线程上运行。这适用于我在其他地方调用的UIApplication其他内容,例如isRegisteredForRemoteNotifications.

该应用程序运行良好,没有崩溃或任何事情,只是来自 Xcode 的警告。

Xcode 只是在这里感到困惑还是我实际上做错了什么?

截屏:

错误截图

编辑:对于那些感到困惑的人MainActor,这是一个有用的阅读:https ://www.swiftbysundell.com/articles/the-main-actor-attribute/

我可以换行UIApplication.shared.open(settingsURL)await MainActor.run但我仍然很困惑为什么MainActor在这里不起作用/为什么 Xcode 认为调用了错误的方法。

4

1 回答 1

-1

该错误表明您可能Task {...}在代码中的某个位置使用了不在主线程上的位置。使用以下测试代码,我无法使用 macos 12.3 Beta、Xcode 13.3、针对 ios 15 和 macCatalyst 12 复制您的问题。在真实设备上测试,而不是预览版。在旧系统上可能会有所不同。

这是我在测试中使用的代码:

struct ContentView: View {
    var body: some View {
        Text("testing")
            .onAppear {
                Task {
                    guard let settingsURL = URL(string: "https://duckduckgo.com") else { return }
                    await UIApplication.shared.open(settingsURL) // <-- NO runtime warning when called
                }
            }
    }
}

此代码是否给您同样的警告?

EDIT-1:这也适用于我。

struct ContentView: View {
    var body: some View {
        Text("testing")
            .onAppear {
                DispatchQueue.global(qos: .background).async {
                    Task {
                        guard let settingsURL = URL(string: "https://duckduckgo.com") else { return }
                        await UIApplication.shared.open(settingsURL)
                    }
                }
            }
    }
}
于 2022-02-12T01:27:21.493 回答