SwiftUI:以编程方式解除警报

SwiftUI:以编程方式解除警报,swiftui,Swiftui,我有一个警报,如果位置服务关闭或被拒绝,将弹出该警报,该警报将引导用户进行设置,以便可以打开位置服务。通过将状态变量showAlert设置为true来显示。我的密码是: Alert(title: Text("Location Services"), message: Text("Location Services is off or denied. The app must have your location to fun

我有一个警报,如果位置服务关闭或被拒绝,将弹出该警报,该警报将引导用户进行设置,以便可以打开位置服务。通过将状态变量showAlert设置为true来显示。我的密码是:

Alert(title: Text("Location Services"),
                     message: Text("Location Services is off or denied. The app must have your location to function. Please enable Location Services for the app in Settings."),
                     primaryButton: .default(Text("Settings"), action: {
                        self.showAlert = false // my attempt to clear the alert
                        UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
                     }),
                     secondaryButton: .default(Text("Okay")))
我遇到的问题是,当用户单击“设置”按钮转到“设置”打开位置服务时,警报不会消失。因此,当用户在启用后返回应用程序时
对于他们,警报仍然存在,说明服务未打开。这是一个糟糕的用户体验,我希望在用户返回后可以阅读它之前将其删除。正如您从代码中看到的,我尝试将showAlert状态变量设置为false,但没有成功。有什么想法吗?

我想这是由于应用程序变得不活动,所以丢失了事件。试试下面的方法

 primaryButton: .default(Text("Settings"), action: {
    // delay action a bit, to give chance to close alert
    DispatchQueue.main.async {
       UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
    }
 }),

我认为这是由于应用程序变得不活动,所以丢失了事件。试试下面的方法

 primaryButton: .default(Text("Settings"), action: {
    // delay action a bit, to give chance to close alert
    DispatchQueue.main.async {
       UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
    }
 }),

非常感谢。成功了!我使用了延迟计时,一直到现在+0.01,工作正常,没有明显的延迟。半秒钟的时间让人感觉界面卡住了,对于将来使用它的任何人来说。@Yrb,那么值得一试的是
DispatchQueue.main.async{…}
,它也可以工作。这将值得重新编辑解决方案。节省几个周期,代码更干净。谢谢!成功了!我使用了延迟计时,一直到现在+0.01,工作正常,没有明显的延迟。半秒钟的时间让人感觉界面卡住了,对于将来使用它的任何人来说。@Yrb,那么值得一试的是
DispatchQueue.main.async{…}
,它也可以工作。这将值得重新编辑解决方案。节省几个周期,代码就更干净了。