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 Source Code CKModifyRecordsOperation Class Reference - We use this class to get more control about how records are saved. 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!