SwiftUI 中是否有等效的 openSettingsURLString?

Is there an equivalent of openSettingsURLString in SwiftUI?

我想创建一个警报,在用户第一次拒绝使用相机后将其重定向到设置应用程序,但到目前为止我看到的唯一方法是使用 UIKit 和

let settingsAction = UIAlertAction(title: "Settings", style: .default, handler: {action in
        UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
    })

在 SwiftUI 中,alert 中有一个 actions 选项,我如何才能通过 SwiftUI 版本的 alert 正确打开设置?

.alert(isPresented: $alertVisible) { () -> Alert in Alert (title: Text("Camera access required to take photos"), message: Text("Go to Settings?"), 
     primaryButton: .default(Text("Settings"), action: UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)), 
     secondaryButton: .default(Text("Cancel"))

在这里

.alert(isPresented: $alertVisible) {
     Alert (title: Text("Camera access required to take photos"),
            message: Text("Go to Settings?"),
            primaryButton: .default(Text("Settings"), action: {
                UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
            }),
            secondaryButton: .default(Text("Cancel")))
        }

这是解决方案(参见@rmaddy 在 [link][1] 的回答):

.alert(isPresented: $showLibraryPicker, content: {
            Alert(title: Text("Camera access required to take photos"),
                  message: Text("Go to Settings?"),
                  primaryButton: .default(Text("Settings"),
                                          action: {
                                            let url: String
                                            #if targetEnvironment(macCatalyst)
                                            url = "x-apple.systempreferences:com.apple.preference.security?Privacy_Photos"
                                            #else
                                            url = UIApplication.openSettingsURLString
                                            #endif
                                            UIApplication.shared.open(URL(string: url)!)
                                          }), secondaryButton: .default(Text("Cancel")))
        })


  [1]: 

在最短的形式中,你可以使用这样的东西:

Link("Open settings ?", destination: URL(string: UIApplication.openSettingsURLString)!)

这将为您创建一个外观简单的按钮,该按钮将直接指向“设置”应用。当然,您可以使用视图修饰符进一步自定义外观。


或者,如果您需要更多控制,您可以在视图中使用 openURL @Environment 属性 包装器,如下所示:

struct SomeView: View {
    @Environment(\.openURL) var openURL

    var body: some View {
        Button(action: openSettings) {
            Label("Open settings?", systemImage: "gear")
        }
    }

    private func openSettings() {
        openURL(URL(string: UIApplication.openSettingsURLString)!)
    }
}