Topics

#28: Discovering Users in CloudKit 👤⛅️

Topics

We continue our tour through CloudKit today with a look at CKDiscoveredUserInfo and it's associated functions. CKDiscoveredUserInfo actually pop up in two different use cases: Grabbing the user's first and last name as well as letting them discover their friends who are also using your app. Let's get started, first we request permission:

let container = CKContainer.defaultContainer()

container.requestApplicationPermission(.PermissionUserDiscoverability) { (status, error) in
    guard error == nil else { return }

    if status == CKApplicationPermissionStatus.Granted {
      // yay!
    }
}

Then we fetch the current user's CKRecord, and fetch their name:

container.fetchUserRecordIDWithCompletionHandler { (recordID, error) in
  guard error == nil else { return }
  guard let recordID = recordID else { return }

  container.discoverUserInfoWithUserRecordID(recordID) { (info, fetchError) in
    // use info.firstName and info.lastName however you need
  }
}

All that's left is to let the user discover their friends:

container.discoverAllContactUserInfosWithCompletionHandler { (users, error) in
  guard error == nil else { return }
  guard let users = users as [CKDiscoveredUserInfo] else { return }

  for user in users {
    // use user.userRecordID to make
    // whatever connections you need
  }
}