OK, just figure out how to share a CKRecord.
It must be done on real device, simulator won't works.
@IBAction func shareButtonItemDidTap(_ sender: UIBarButtonItem) {
let controller = UICloudSharingController { controller, preparationCompletionHandler in
// this block called when user select a destiniation to share. either copy link, or share to Twitter, Facebook etc.
print("prepare for sharing")
let privateDatabase = CKContainer.default().privateCloudDatabase
// create and save zone if needed
let zoneID = CKRecordZoneID(zoneName: "MyUniqueRecordZoneName", ownerName: CKCurrentUserDefaultName)
let zone = CKRecordZone(zoneID: zoneID)
let modifyRecordZonesOperation = CKModifyRecordZonesOperation(recordZonesToSave: [zone],
recordZoneIDsToDelete: nil)
modifyRecordZonesOperation.timeoutIntervalForRequest = 10
modifyRecordZonesOperation.timeoutIntervalForResource = 10
modifyRecordZonesOperation.modifyRecordZonesCompletionBlock = { zone, _, error in
if let error = error as? CKError {
print("modifyRecordZonesOperation error:", error)
preparationCompletionHandler(nil, nil, error)
return
}
// create, save and share a record. as example, share a simple image record
let recordID = CKRecordID(recordName: UUID().uuidString, zoneID: zoneID)
let record = CKRecord(recordType: "Image", recordID: recordID)
record["image"] = UIImagePNGRepresentation(#imageLiteral(resourceName: "sample image"))! as CKRecordValue
// Documentation Note: When saving a newly created CKShare, you must save the share and its rootRecord in the same CKModifyRecordsOperation batch.
let share = CKShare(rootRecord: record)
share[CKShareTitleKey] = "My Amazing Image!!" as CKRecordValue
let modifyRecordsOperation = CKModifyRecordsOperation(recordsToSave: [record, share], recordIDsToDelete: nil)
modifyRecordsOperation.timeoutIntervalForRequest = 10
modifyRecordsOperation.timeoutIntervalForResource = 10
modifyRecordsOperation.modifyRecordsCompletionBlock = { records, recordIDs, error in
if let error = error as? CKError {
print("modifyRecordsOperation error:", error)
}
preparationCompletionHandler(share, CKContainer.default(), error)
}
privateDatabase.add(modifyRecordsOperation)
}
privateDatabase.add(modifyRecordZonesOperation)
}
controller.availablePermissions = [.allowPublic, .allowReadOnly]
controller.popoverPresentationController?.barButtonItem = sender
present(controller, animated: true)
}