我如何“通过电子邮件向我看”

时间:2016-03-02 12:13:54

标签: ios icloud icloud-drive

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

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

1 个答案:

答案 0 :(得分:3)

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

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)