授予联系权限后更改视图

时间:2020-06-04 19:56:18

标签: swift swiftui cncontactstore ios-contacts

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

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
    }
}) 

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

1 个答案:

答案 0 :(得分:1)

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
       }
    }

  }
})