CKRecord Upload Progress

Episode #269 | 6 minutes | published on May 11, 2017 | Uses iOS-10.3, Xcode-8.3
Subscribers Only
Saving records includes uploading any attached assets. For a good user experience, we should show the user the progress for any records that are being saved (or downloaded). In this episode we’ll see how we can get that data and show a progress bar for uploading photos. To do this we will take a look at a new class, CKModifyRecordsOperation.

Episode Links

Migrating to CKModifyRecordsOperation

The previous CKDatabase.save() function is a simple convenience wrapper around CKModifyRecordsOperation, and as such it doesn't give us all the control and functionality.

To track progress, we’ll have to migrate over to this new class.

let modifyOp = CKModifyRecordsOperation(
    recordsToSave: [photo.record],
    recordIDsToDelete: nil
)

Setting the Blocks for Progress and Completion

This is also how you batch saves together in a single call, which saves the round-trip cost for saving many things at once.

We have to fill out a few blocks on this operation to get it working:

This block will be called when the photo(s) have finished uploading...

modifyOp.modifyRecordsCompletionBlock = { records, _, error in
    if let e = error {
        print("Error saving photo: \(e)")
    } else {
        self.prepend(photo: photo)
    }

And this block will be called for per-record completion percentage...

 modifyOp.perRecordProgressBlock = { record, progress in       
    DispatchQueue.main.async {
        self.progressView.setProgress(Float(progress), animated: true)
    }            
}

Make sure you are on the main thread before updating any UI element, since these are called from a different thread.

Starting the Operation

Like the rest of CloudKit, we'll have to add this operation to a database to get it running:

database.add(modifyOp)

Build and run and you’ll be able to upload a new photo and see progress during the upload!

blog comments powered by Disqus