授予联系人权限后更改视图



目前,我能够成功地请求用户允许他们访问他们的联系信息。我正在通过这样的开关语句来处理这个问题:

func requestContactPermissions() {
let store = CNContactStore()
var authStatus = CNContactStore.authorizationStatus(for: .contacts)
switch authStatus {
case .restricted:
print("User cannot grant permission, e.g. parental controls in force.")
exit(1)
case .denied:
print("User has explicitly denied permission.")
print("They have to grant it via Preferences app if they change their mind.")
exit(1)
case .notDetermined:
print("You need to request authorization via the API now.")
store.requestAccess(for: .contacts) { success, error in
if let error = error {
print("Not authorized to access contacts. Error = (String(describing: error))")
exit(1)
}
if success {
print("Access granted")
}
}
case .authorized:
print("You are already authorized.")
@unknown default:
print("unknown case")
}
}

.notDetermined情况下,这是打开对话框,我可以在其中单击noyes,授予或拒绝应用程序访问权限。这很好,也是意料之中的。

我要做的是,如果用户单击yes,则更改视图。现在,我在按钮中具有requestContactPermissions功能,如下所示:

Button(action: {
withAnimation {
// TODO: Screen should not change until access is successfully given.
requestContactPermissions()
// This is where the view change is occurring.
self.loginSignupScreen = .findFriendsResults
}
}) 

如何在用户授予应用程序对其联系人的访问权限后添加逻辑以更改视图?

requestContactPermissions函数添加一个补全,如下所示(我修剪了答案的不相关部分(:

func requestContactPermissions(completion: @escaping (Bool) -> ()) {
let store = CNContactStore()
var authStatus = CNContactStore.authorizationStatus(for: .contacts)
switch authStatus {
case .notDetermined:
print("You need to request authorization via the API now.")
store.requestAccess(for: .contacts) { success, error in
if let error = error {
print("Not authorized to access contacts. Error = (String(describing: error))")
exit(1)
//call completion for failure
completion(false)
}
if success {
//call completion for success
completion(true)
print("Access granted")
}
}
}
}

然后,您可以在闭包中确定用户是否授予了权限:

Button(action: {
withAnimation {
// TODO: Screen should not change until access is successfully given.
requestContactPermissions { didGrantPermission in
if didGrantPermission {
//this is the part where you know if the user granted permission:
// This is where the view change is occurring.
self.loginSignupScreen = .findFriendsResults
}
}
}
}) 

最新更新