如何使用 CloudKit 的 CKShare 创建共享?

How to create a share with CloudKit's CKShare?

我正在研究 Apple 今年发布的新 CKShare,我对它有一些疑问。我试图关注 WWDC 的 "What's new in CloudKit" 视频,但部分代码在 Xcode.

中不再起作用

我想做的是:用户将输入他的姓名和 phone,然后在单击 UIButton 后与特定的人共享。这是代码:

class ViewController: UIViewController, UICloudSharingControllerDelegate {
    @IBOutlet weak var nome: UITextField!
    @IBOutlet weak var telefone: UITextField!
    @IBOutlet weak var button: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func send(_ sender: AnyObject) {
        print("Send button was clicked.\n")

        let elder = CKRecord(recordType: "Elder")
        elder["name"] = self.name.text as CKRecordValue?
        elder["telephone"] = self.telephone.text as CKRecordValue?

        let ckContainer = CKContainer.default()
        let shareRecord = CKShare(rootRecord: elder)

        shareRecord[CKShareTitleKey] = "Elder" as CKRecordValue?

        let shareController = UICloudSharingController(share: shareRecord, container: ckContainer)
        shareController.delegate = self
        shareController.availablePermissions = [.allowReadOnly]
        shareController.popoverPresentationController?.sourceView = self.button

        self.present(shareController, animated: true)
    }

    func cloudSharingController(_ csc: UICloudSharingController, failedToSaveShareWithError error: Error) {
        print("PROBLEM SAVING SHARE")
    }

    func cloudSharingControllerDidSaveShare(_ csc: UICloudSharingController) {
        print("SHARE SAVED")
    }

    func itemTitle(for csc: UICloudSharingController) -> String? {
        return "a"   //don't know what this is for
    }
}

即使 CloudSharingController 出现,我的应用程序仍在打印 "PROBLEM SAVING SHARE"。此外,CKRecord elder 没有出现在 CloudKit 的仪表板中。

有人告诉我,只有当共享已经创建时,您才能使用您选择使用的初始化程序。对于新共享,使用备用初始化

试试这个代码:

let csc = UICloudSharingController { controller,
        preparationCompletionHandler in
        let share = CKShare(rootRecord: elder)

        let mro = CKModifyRecordsOperation(
            recordsToSave: [elder, share],
            recordIDsToDelete: nil)


        mro.modifyRecordsCompletionBlock = {
            records, recordIDs, error in
            if error != nil {
                    //handle error
            }
            preparationCompletionHandler(share,CKContainer.default(), error)
        }
        myDB.add(mro)
    }

    csc.delegate = self
    self.present(csc, animated:true, completion:nil)

所以,我发现出了什么问题...我使用的是云工具包为您创建的默认区域,而您在使用 CKShare 时无法这样做。 您所要做的就是创建一个私有自定义 CKZone 并将 CKRecord 和 CKShare 保存在其中!