Handing a completion with CloudKit

Handing a completion with CloudKit

By : user2173212
Date : October 21 2020, 08:10 AM
To fix this issue I'm kind of concerned that both the previous answers don't help answer your question.. One is asking you to restructure your database and the other is asking you to become dependent on a third-party library.
My suggestion would be to make your perform(_:inZoneWith:) into a synchronous operation so that you can easily perform one after another. For example:
code :
func performSynchronously(query: CKQuery) throws -> [CKRecord] {

    var errorResult: Error?
    var recordsResult: [CKRecord]?
    let semaphore = DispatchSemaphore(value: 0)

    CKDbase.share.privateDB!.perform(query, inZoneWith: nil) { records, error in
        recordsResult = records
        errorResult = error

    // Block this thread until `semaphore.signal()` occurs

    if let error = errorResult {
        throw error
    } else {
        return recordsResult ?? []
// ... start your activity indicator

DispatchQueue(label: "background").async {

    do {
        let records1 = try performSynchronously(query: CKQuery...)
        // parse records1
        let records2 = try performSynchronously(query: CKQuery...)
        // parse records2

        DispatchQueue.main.async {
            // stop your activity indicator

    } catch let e {
        // The error e occurred, handle it and stop the activity indicator

Share : facebook icon twitter icon
iOS CloudKit crash on completion block for -fetchUserRecordIDWithCompletionHandler:

iOS CloudKit crash on completion block for -fetchUserRecordIDWithCompletionHandler:

By : chen's
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Okay, so I did figure this one out.
I rolled back to the last working and changed everything except for some binaries generated by FastPDFKit. After I did that it started working fine. No clue what in there was messing it up but it works now.
How to invoke completion block in CloudKit in Swift 2 in iOS 9?

How to invoke completion block in CloudKit in Swift 2 in iOS 9?

By : user3820173
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I did not managed to translate my working iOS8 code snippet into iOS 9 Swift 2 Xcode version 7.0 beta (7A120f). , Ok, here is the solution:
code :
       saveRecordsOperation.perRecordCompletionBlock = {
            (record:CKRecord?, error:NSError?) -> Void in

            print("perRecordCompletionBlock \(record)")
Adding a completion block to a CloudKit function

Adding a completion block to a CloudKit function

By : Jornny
Date : March 29 2020, 07:55 AM
Does that help You need to pass a block as a parameter to the loadExpenses() function. So it should actually be defined something like loadExpenses(completionBlock:([whatever parameters you need in here])->Void).
Then, you can call the passed completionBlock block (with appropriate parameters) from within the operation.queryCompletionBlock block.
code :
func loadExpenses(completionBlock:([Expense])->Void) {
    let pred = NSPredicate(value: true)
    let sort = NSSortDescriptor(key: "creationDate", ascending: true)
    let query = CKQuery(recordType: "Expense", predicate: pred)
    query.sortDescriptors = [sort]

    let operation = CKQueryOperation(query: query)
    operation.desiredKeys = ["person", "action", "amount", "timestamp"]
    operation.resultsLimit = 50

    var newExpenses = [Expense]()

    operation.recordFetchedBlock = { (record) in
        let recordID = record.recordID
        let person = record["person"] as! String
        let action = record["action"] as! String
        let amount = record["amount"] as! Double
        let timestamp = record["timestamp"] as! NSDate
        let expense = Expense(person: person, action: action, amount: amount, timestamp: timestamp)

    // This is the part that needs to be changed
    operation.queryCompletionBlock = { [unowned self] (cursor, error) in
loadExpenses({ (newExpenses:[Expense]) -> Void in {
    dispatch_async(dispatch_get_main_queue()) {
        if error == nil {
            self.objects = newExpenses
        } else {
            let ac = UIAlertController(title: "Fetch failed", message: "There was a problem fetching the list of expenses; please try again: \(error!.localizedDescription)", preferredStyle: .Alert)
            ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
            self.presentViewController(ac, animated: true, completion: nil)
CloudKit completion handler and dispatch_sync issue

CloudKit completion handler and dispatch_sync issue

By : Goofy9020
Date : March 29 2020, 07:55 AM
should help you out Indeed there can be some time between saving data and being able to retrieve it. There is no specification how long this could be. Usually it's less than seconds.
So you have to make your app logic so that it does not care about that. You already saved the record so your app already knows the content of that record. You could pass on the record from the callback so that you don't have to query for it again.
Completion Block handing empty array

Completion Block handing empty array

By : Justin MacCreery
Date : March 29 2020, 07:55 AM
Any of those help You are calling completeBlock(result: collectionArray) outside the completion block for the query. Move it inside the query's completion block instead of after.
You have:
code :
    query.findObjectsInBackground(block: { (objects, error) in
        // lots of stuff removed for clarity

    completeBlock(result: collectionArray)
    query.findObjectsInBackground(block: { (objects, error) in
        // lots of stuff removed for clarity

        completeBlock(result: collectionArray)
Related Posts Related Posts :
  • Managing cookies for a domain in Associated Domains
  • Array items showing error in IOS
  • Saving asynchronously downloaded files' contents to SQLITE
  • Swift 4 - animating both alpha and constraint affects other components alpha value
  • UIView animation in completion block starts with displacement
  • List all Apps and Track Internet Usage
  • Handling Back To Back HTTP Posts SWIFT 4.0
  • Azure App Service Push - registration endpoint
  • Select multiple item in a tableView
  • Apartment number / Unit number returned from google places api
  • How to align UICollectionViewCells from left to right?
  • How can I add search option on UIPickerview in ios?
  • Scenekit - physicsWorld setup to prevent kinematic nodes to intersect
  • Carthage Build Failed
  • swift 3, ios 10 - push notification firebase is not received
  • App Xcode 8 to Xcode 9 - Prevent Auto Hide Status Bar
  • How to pop back to a TableViewController?
  • Is UserDefaults thread safe in Swift? How to check it?
  • UISwitch in a table selects multiple cells when switch state on
  • iOS App with no story board (Size classes and Device type limitations)
  • AudioKit issue, mic not sensitive enough
  • send indexpath to Firebase (like button)
  • UIColor saturation brightness values different from the regular saturation luminosity values of a color
  • JSON: Extracting Data Using Alamofire and Swift 3
  • invalid_grant on OAuth2 request when obtaining access_token from SSO in App
  • ABNewPersonViewController using contact framework
  • Design iOS button scalable
  • Subclassing NSLayoutConstraint constant based on screen height
  • Migrate Realm 2.x List of Object to Realm 3.x List of String (or other primary type)
  • Using BLE RSSI value for connect-by-proximity
  • Backgroundcolor of NSTextfield
  • Firebase modifying uid in every view
  • How to rotate orientation?
  • Upload a new version of ios app to app store?
  • UIScrollView do not scroll down to its original position when keyboard disappear
  • What is the most effective way of tracking time/dates in an iOS/Swift application?
  • WatchKit get user's preferred handedness
  • Location permission dialog is shown and immediately disappears
  • Combine these regex expressions
  • How to save an array of HKQuantitySamples (heart rate) to a workout
  • RestKit mapping with parent key as attribute and key contains parenthesis
  • How to add UITextField programmatically to UIScrollView without breaking constraints?
  • How to make a view height grow depending on its child views contents
  • Some users experiencing NSInternalInconsistencyException crash
  • Mark successful siesta response as error
  • Using a modified PDFTron Tools Framework
  • How can I use universal links when I call openURL inside my own app?
  • NSArray of doubles iOS (Objective c)
  • Passing data from embedded PageViewController to parent View Controller
  • Reuse item inside a row when scrolling
  • Realm Relation how to implement
  • error: generic parameter 'T' could not be inferred in swift
  • Adding shadow to UITextView makes text expand out of UITextViewFrame
  • How to change the string in seconds to minutes in Swift3?
  • Search bar is refreshing the index of my table view cell
  • Decodable multiple DateDecodingStrategies
  • The spoiled simulator xcode 9. As a broken TV
  • How to set width of TouchableWithoutFeedback depends on Text in react-native?
  • How to show an UIActivityIndicatorView whitin UITableViewController?
  • UItextfield text in Custom UITableViewCell prints nil when i scroll up in SE
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org