【发布时间】:2023-03-24 23:25:01
【问题描述】:
我调用了一个函数来访问用户的联系信息。但是,如果授权状态被拒绝,我需要这个功能来提示用户一个警报,可以将他们重定向到他们的设置页面。
到目前为止,我的代码成功提示用户输入他们的联系信息。但是,如果案例最终被拒绝,我想运行show_settings_alert 函数,如下所示:
func requestContactPermissions(completion: @escaping (Bool) -> ()) {
let store = CNContactStore()
var authStatus = CNContactStore.authorizationStatus(for: .contacts)
switch authStatus {
case .denied:
show_settings_alert()
}
这是我在一些关于此问题的教程中找到的 show_settings_alert 函数:
func show_settings_alert() {
let alertController = UIAlertController(title: "TITLE", message: "Please go to Settings and turn on the permissions", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in })
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(cancelAction)
alertController.addAction(settingsAction)
self.present(alertController, animated: true, completion: nil)
}
问题是,我试图在函数中运行self.present,因此我无法访问 self.我也知道这是 UIKit 代码,我不完全确定如何在使用 SwiftUI 时获得相同的功能。
我知道 SwiftUI 附带了一个 Alert 类,但我不想在我的模板视图中包含这个逻辑。
【问题讨论】: