logo
down
shadow

How to update all client records from CloudKit?


How to update all client records from CloudKit?

By : Adrien André
Date : November 19 2020, 01:01 AM
I hope this helps . CloudKit has the CKFetchRecordChangesOperation for this. You can request all changes within a zone since the previous update. You can then synchronize that data with the storage inside your app.
If you do use subscriptions, then if there are multiple notifications send in a short period, there is a big chancre that your app won't get all notifications. Apple will limit that. This is why after processing received subscription notifications you should also execute a CKFetchNotificationChangesOperation after you received a notification.
code :


Share : facebook icon twitter icon
Client oplock error, saving records in CloudKit

Client oplock error, saving records in CloudKit


By : Tomás Macías Rivas
Date : March 29 2020, 07:55 AM
like below fixes the issue You are getting this error because the version of the User record on the server is newer than what you're trying to update it with. If you take the error code rawValue (14) and map it to the CKErrorCode enum, you see it maps to:
code :
CKErrorCode.ServerRecordChanged /* The record was rejected because the version
                                   on the server was different */
public enum CKErrorCode : Int { 
  case InternalError /* CloudKit.framework encountered an error.  This is a non-recoverable error. */
  case PartialFailure /* Some items failed, but the operation succeeded overall */
  case NetworkUnavailable /* Network not available */
  case NetworkFailure /* Network error (available but CFNetwork gave us an error) */
  case BadContainer /* Un-provisioned or unauthorized container. Try provisioning the container before retrying the operation. */
  case ServiceUnavailable /* Service unavailable */
  case RequestRateLimited /* Client is being rate limited */
  case MissingEntitlement /* Missing entitlement */
  case NotAuthenticated /* Not authenticated (writing without being logged in, no user record) */
  case PermissionFailure /* Access failure (save or fetch) */
  case UnknownItem /* Record does not exist */
  case InvalidArguments /* Bad client request (bad record graph, malformed predicate) */
  case ResultsTruncated /* Query results were truncated by the server */
  case ServerRecordChanged /* The record was rejected because the version on the server was different */
  case ServerRejectedRequest /* The server rejected this request.  This is a non-recoverable error */
  case AssetFileNotFound /* Asset file was not found */
  case AssetFileModified /* Asset file content was modified while being saved */
  case IncompatibleVersion /* App version is less than the minimum allowed version */
  case ConstraintViolation /* The server rejected the request because there was a conflict with a unique field. */
  case OperationCancelled /* A CKOperation was explicitly cancelled */
  case ChangeTokenExpired /* The previousServerChangeToken value is too old and the client must re-sync from scratch */
  case BatchRequestFailed /* One of the items in this batch operation failed in a zone with atomic updates, so the entire batch was rejected. */
  case ZoneBusy /* The server is too busy to handle this zone operation. Try the operation again in a few seconds. */
  case BadDatabase /* Operation could not be completed on the given database. Likely caused by attempting to modify zones in the public database. */
  case QuotaExceeded /* Saving a record would exceed quota */
  case ZoneNotFound /* The specified zone does not exist on the server */
  case LimitExceeded /* The request to the server was too large. Retry this request as a smaller batch. */
  case UserDeletedZone /* The user deleted this zone through the settings UI. Your client should either remove its local data or prompt the user before attempting to re-upload any data to this zone. */
}
Can't have more than 100 records in CloudKit

Can't have more than 100 records in CloudKit


By : CATL
Date : March 29 2020, 07:55 AM
seems to work fine On iOS 9.3 and below you'll need to use CKQueryCursor to perform multiple fetch operations and keep track of where you were at in the fetch. Thats the cursor object that got passed back in the completion block, you can create another operation with it which will pick up off where you left it like so:
code :
queryOperation.queryCompletionBlock = { (cursor, error) in
    if let cursor = cursor {
         let cursorOperation = CKQueryOperation(cursor: cursor)
         cursorOperation.queryCompletionBlock = //Handle it again
    }
    //Do stuff
}
How to update data in TableView without the delay using CloudKit when Creating new Records

How to update data in TableView without the delay using CloudKit when Creating new Records


By : Huan
Date : March 29 2020, 07:55 AM
wish help you to fix your issue There is no guarantee as to when the record would be available in a query but there is something you can do. You can stitch the new record back in. Because when you create and save a record you have the record id you can make a ckfetchrecordsoperation and pass the id from the new record and you are guaranteed to get it back immediately. The indexing sometimes can take a while and this is frustrating with CloudKit. So basically the best way to guarantee a speedy database is make a query and if the new record id is not in there make a fetch with the id and append it to your results. Hope this makes sense.
I had to do this before and since I have not been too keen on CK. Here is the link to the operation to stitch the record back in. https://developer.apple.com/reference/cloudkit/ckfetchrecordsoperation also if you are using images check out this library I made that allows you to exclude the image data keys and download and cache on demand that could speed up your queries. https://github.com/agibson73/AGCKImage
code :
   func loadRecordsFromiCloud() {

    // Get a private Database
    let privateDatabase = CKContainer.default().privateCloudDatabase
    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "MyRecords", predicate: predicate)

    privateDatabase.perform(query, inZoneWith: nil) { (results, error) in
        if ((error) != nil) {
            // Error handling for failed fetch from public database
            print("error loading : \(error)")

        }
        else {
            //check for a newRecord ID that might be missing from viewcontroller 2 that was passed back
            if self.passedBackNewRecordID != nil{
                let newResults = results?.filter({$0.recordID == self.passedBackNewRecordID})
                //only excute if there is a new record that is missing from the query
                if newResults?.count == 0{
                    //houston there is a problem
                    let additionalOperation = CKFetchRecordsOperation(recordIDs: [self.passedBackNewRecordID!])
                    additionalOperation.fetchRecordsCompletionBlock = { recordsDict,fetchError in
                        if let newRecords = recordsDict?.values as? [CKRecord]{
                            //stitch the missing record back in
                            let final = newRecords.flatMap({$0}) + results!.flatMap({$0})
                            self.reloadWithResults(results: final)
                            self.passedBackNewRecordID = nil

                        }else{
                            self.reloadWithResults(results: results)
                            self.passedBackNewRecordID = nil
                        }

                    }
                    privateDatabase.add(additionalOperation)
                 }else{
                    //the new record is already in the query result
                    self.reloadWithResults(results: results)
                    self.passedBackNewRecordID = nil
                }
            }else{
                //no new records missing to do additional check on
                self.reloadWithResults(results: results)
            }

        }
    }
}


func reloadWithResults(results:[CKRecord]?){
       self.tableViewDataArray = results!
        DispatchQueue.main.async {
            print("DispatchQueue.main.sync")
             self.tableView.reloadData()
        }

    }
}
 CloudKitManager.sharedInstance.privateDatabase.save(myRecord) { (savedRecord, error) -> Void in

            if error == nil {


        print("successfully saved record code: \(savedRecord)")
        //save temporarily to defaults
        let recordID = "someID"
        UserDefaults.standard.set(recordID, forKey: "recentlySaved")
        UserDefaults.standard.synchronize()
        //now we can dismiss


            }
            else {
                // Insert error handling
                print("error Saving Data to iCloud: \(error.debugDescription)")
            }
        }
func startQuery(){
    UserDefaults.standard.synchronize()
    if let savedID = UserDefaults.standard.value(forKey: "recentlySaved") as? String{
        passedBackNewRecordID = CKRecordID(recordName: savedID)
        //now we can remove from Userdefualts
        UserDefaults.standard.removeObject(forKey: "recentlySaved")
        UserDefaults.standard.synchronize()
    }

    self.loadRecordsFromiCloud()
}
CloudKit - How to share multiple records and retrieve shared records?

CloudKit - How to share multiple records and retrieve shared records?


By : ahmed
Date : March 29 2020, 07:55 AM
this one helps. I believe Thunk's answer is incorrect, since you should not have to fetch any records with the parent reference to a given record. First, where would you search? The child records of the CKShare root record do not appear in your shared database and you don't have access to the other user's private zone. Luckily, CloudKit will push to you all child records referenced by the CKShare's root record. The following approach will also solve the second problem, you will be notified of any and all future changes automatically!
The key is to simply add a CKDatabaseSubscription to the shared database in the CloudKit container. Let's assume you are the client. Anytime another user share's a record with you, the CKShare record and the underlying root record referenced by the share are both situated in a custom zone in that user's private database. When you accept the share (triggering an application delegate method userDidAcceptCloudKitShareWith), the same CKShare and underlying record are now visible to you, except that they are both visible in your shared database. If you have subscribed to the shared database, the subscription will kick in and notify you right after you accept the share. Now you can fetch all changes in the shared database using CKFetchDatabaseChangesOperation. In the recordZoneWithIDChangedBlock, the CKRecordZoneID of the sharing user's custom zone will be given. You use this to trigger a CKFetchRecordZoneChangesOperation (be sure to perform this operation in the shared database!), which returns the CKShare, the underlying root record, and all records that have a parent reference to the underlying referenced record.
Force iOS CloudKit synchronization update to download all records to local device

Force iOS CloudKit synchronization update to download all records to local device


By : lixuanxia
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I would recommend you just use CKQuery and with a given NSPredicate you will be able to get all the data you need from CloudKit database
Related Posts Related Posts :
  • Unclear about releasing CFDictionaryRef
  • CordovaError: Promise rejected with non-error: Error code 65
  • How to append NSMutable strings into a UILabel
  • CustomCell label value does not change
  • Display ad in iAd Bannerview iAd Network
  • Warning: "Could not get traitsetID for iPhone11,6" (Assets.xcassets)
  • Changing root view controller after iOS app has loaded.
  • SocketRocket and iOS certificate pinning
  • Draggable UIButton Snap To a Circle Path
  • Running FireBase in the background
  • resizing UIPopoverController to fit UITableController
  • UICollectionView Exception Crash
  • targeting iOS5 - will it work on iOS6 also?
  • FBLoginView get email
  • Scale UIImages height to UIImageView height
  • Creating a custom progress indicator in ios
  • NSRunLoop API difference
  • Is it possible to inject custom settings into my iOS application "Notifications" settings dialog?
  • UIAlertview not accepting string as message
  • Axis change of stackView giving layout error
  • How to use AVAssetResourceLoader?
  • How to write block definition using properties?
  • iOS connect/reconnect to Bluetooth device when using external-accessory and MFi
  • Saving XMPP Multi User chat messages through XMPP MessageArchiving in iOS
  • Deciding iOS version: pros and cons
  • iOS: Resigned app cannot access keychain through security API
  • How can I set To and Subject fields in an E-Mail being sent by UIDocumentInteractionController?
  • Updating uilabel in view controller underneath another
  • Maximum time Intervel for NSTimer
  • Delete Core Data Entry from Table View Controller
  • How to unload UIViewcontroller from memory?
  • Compressing UIImage as Far as Possible?
  • Optimizing workflow to update internally owned cocoapods dependencies?
  • Formatting an NSDate with Abbreviated Month/Day Names
  • I'm creating a quiz game with 4 answers and I want to add score
  • Tap Gesture to Hide Navigation Bar, Tab Bar, and Status Bar
  • FBSessionStateClosedLoginFailed when I am logged in through Settings
  • CGRect positioning according to center point
  • iOS: Update table view datasource with animations without core data
  • iOS : Where to start for AliPay integration?
  • Routing App Coverage File missing but not needed?
  • Drawing on a zoomable view
  • Append NSStrings and NSNumber to NSMutableArrays and make NSMutable dictionary
  • Terminating app due to uncaught exception 'NSRangeException' when calling dequeueReusableCellWithReuseIdentifier:forInde
  • Collision without physics (Cocos2D + Box2D iOS)
  • Creating a percentage based iOS layout
  • Update tableView row from AppDelegate Swift 4
  • Assigning return value of a class method to a variable error
  • how to display circular progress in delphi ios apps?
  • I can't figure how to fix this Expected identifier or '('
  • How to Test APIs in Swift 4?
  • Link error /Build/Products/Debug-iphonesimulator file not found
  • working with a very large JSON object in iOS
  • Turn off part of the iPhone Screen
  • Phonegap 3.0 app with facebook login using xCode
  • How to add interstitial admob ads to my ios project
  • adding tapku calendar to ios app
  • Add an alertcontroller in a global swift file?
  • Take square image with Cordova (Phonegap) Camera API?
  • Amazon S3 policy allowing only upload not overwrite
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org