2017-07-14 135 views
0

如何獲取用戶的當前UserId?我正在使用下面的代碼:在CloudKit中獲取當前用戶ID?

CKContainer.default().requestApplicationPermission(.userDiscoverability) { (status, error) in 
     CKContainer.default().fetchUserRecordID { (record, error) in 
      if #available(iOS 10.0, *) { 
       CKContainer.default().discoverUserIdentity(withUserRecordID: record!, completionHandler: { (userID, error) in 
        self.currentuserID = userID?.userRecordID 
        print("user record id") 
        print(userID) 

       }) 
      } else { 
       // Fallback on earlier versions 
      } 
     } 

但是在最後currentUserID被設置爲nill?有誰知道如何成功獲得許可並獲得當前用戶ID?

+0

你在後續的獲取和發現調用之前檢查了錯誤嗎?你在哪裏運行這段代碼?您是否在設備上登錄了iCloud? – agibson007

回答

0

在提取用戶信息之前,您應該檢查status的值。它可能是這樣的...

CKContainer.default().requestApplicationPermission(.userDiscoverability) { (status, error) in 
    switch status 
    { 
     case .granted: 
      print("iCloud is OK") 

     case .initialState: 
      print("The user has not yet decided whether to grant this permission") 
      return 

     case .couldNotComplete: 
      print("An error occurred during the getting or setting of the app permission") 

      if let error = error 
      { 
       print("err @ \(#function) -> \(error.localizedDescription)") 
      } 

      return 

     case .denied: 
      print("The user denied access to the permission.") 
      return 
    } 

    CKContainer.default().fetchUserRecordID { (record, error) in 
     if #available(iOS 10.0, *) 
     { 
      CKContainer.default().discoverUserIdentity(withUserRecordID: record!, completionHandler: { (userID, error) in 
       self.currentuserID = userID?.userRecordID 
       print("user record id") 
       print(userID) 

      }) 
     } 
     else 
     { 
      // Fallback on earlier versions 
     } 
    }