CloudKit - 如何取消正在进行的 Save/Upload 操作

CloudKit -How to Cancel a Save/Upload Operation that's in Progress

有没有办法取消正在进行的 CloudKit 保存或上传操作?

这不是 time-out 情况。我注意到上传视频需要一些时间,用户可能会决定关闭 vc。如果他们这样做,我想取消当前的上传。

let database = CKContainer.default().publicCloudDatabase

var operation: CKModifyRecordsOperation?

func save(videoURL: URL) {

    let record = CKRecord(recordType: "MyType")
    let fileURL = URL(fileURLWithPath: videoURL.path)
    let asset = CKAsset(fileURL: fileURL)
    record["videoAsset"] = asset

    database.save(record) { (record, err) in
    }

    // or

    operation = CKModifyRecordsOperation(recordsToSave: [record], recordIDsToDelete: nil)
    operation?.savePolicy = .allKeys
    operation?.modifyRecordsCompletionBlock = { (savedRecordIDs, deletedRecordsIDs, error) in
    }

    database.add(operation!)
}

既然你有对CKModifyRecordsOperation的引用,你可以调用cancel

operation?.cancel()

如果您查找 CKModifyRecordsOperation 的文档,它会说以下内容。

If you assign a completion handler to the completionBlock property of the operation, CloudKit calls it after the operation executes and returns the results. Use the completion handler to perform any housekeeping tasks for the operation, but don’t use it to process the results of the operation. The completion handler you provide should manage any failures of the operation, whether due to an error or an explicit cancellation.