1

我正在制作一个 iOS 应用程序,我想使用 iOS 设置中 iCloud 下的 iCloud 功能“通过电子邮件查找我”。

我想通过 iCloud 识别用户来简化用户体验,这样他们就不必记住我的应用程序的登录信息。

4

1 回答 1

3

据我了解,这是与CKDiscoverAllContactsOperation. 您可以使用相同的应用程序从您的联系人中发现人,并且可以被他们发现。您需要首先请求该功能的许可,如下所示:

CKContainer.defaultContainer().requestApplicationPermission(CKApplicationPermissions.UserDiscoverability) { [unowned self] (status, error) -> Void in
   //Your code handling error or success...
}

笔记

iOS 10 的发行说明中提到,此操作和相关功能将有所更改。在 iOS 10+ 中你需要使用CKDiscoverAllUserIdentitiesOperation

使用示例

先初始化一个容器,注意你的容器accountStatus必须是正确的

let container = CKContainer(identifier: "iCloud.com.YourContainerID")

稍后,请求许可

container.requestApplicationPermission(CKApplicationPermissions.userDiscoverability) { [unowned self] (status, error) -> Void in     
   if let err = error {
      print(err)
   }
   else if status == CKApplicationPermissionStatus.granted{
      //success
   }
   else{
      print("Permission not granted")
      print(status)
   }
}

稍后,您可以获取当前用户记录 ID 并创建订阅(请注意,您不需要权限和用户记录 ID 来创建订阅,但在我的情况下需要创建谓词):

container.fetchUserRecordID { [weak self] (recordID, error) in

    let predicate = NSPredicate(format: "user = %@",userRecordID.recordName)
    let subscription = CKSubscription(recordType: "myRecordType", predicate: predicate, options: CKSubscriptionOptions.firesOnRecordCreation)

    container.publicCloudDatabase.save(subscription, completionHandler: { (subscription, error) in 
        //completion stuff here
    }
}

朋友可发现性示例

let discoverOperation = CKDiscoverAllUserIdentitiesOperation()

var users = [CKUserIdentity]()

discoverOperation.discoverAllUserIdentitiesCompletionBlock = { [weak self] (error: Error?) -> Void in

   if let err = error as? NSError{
      print("Discover Friends Error: \(err)")
   } else {    
      //do whatever you want with discovered contacts
   }
}

discoverOperation.userIdentityDiscoveredBlock = { (userIdentity: CKUserIdentity) -> Void in
   users.append(userIdentity)
}

discoverOperation.queuePriority = Operation.QueuePriority.high //this option is up to your tasks
container.add(discoverOperation)
于 2016-08-23T11:48:53.300 回答