Swift Core Data Sync With Web Server
Add new
BOOL
attribute
to yourCoreData Entity
and name it assynched
. This will basically store the synched status for each object.Now you will have to check for internet connectivity. Refer to this link
Whenever you have internet connectivity, just fetch the objects from
CoreData
using the followingNSPredicate
in your fetch request:let isSynchedPredicate = NSPredicate(format: "synched = %@", false)
Now you can just use your webservice to sync and update all the fetched objects to server. On successfull upload, DONOT forget to change the
synched
property totrue
How to sync data from web service with Core Data?
You are running into the classic insert/update/delete paradigm.
The answer is, it depends. If you get a chunk of json data then you can use KVC to extract the unique ids from that chunk and do a fetch against your context to find out what exists already. From there it is a simple loop over the chunk of data, inserting and updating as appropriate.
If you do not get the data in a nice chunk like that then you will probably need to do a fetch for each record to determine if it is an insert or update. That is far more expensive and should be avoided. Batch fetching before hand is recommended.
Deleting is just about as expensive as fetching/updating since you need to fetch the objects to delete them anyway so you might as well handle updating properly instead.
Update
Yes there is an efficient way of building the dictionary out of the Core Data objects. Once you get your array of existing objects back from Core Data, you can turn it into a dictionary with:
NSArray *array = ...; //Results from Core Data fetch
NSDictionary *objectMap = [NSDictionary dictionaryWithObjects:array forKeys:[array valueForKey:@"identifier"]];
This assumes that you have an attribute called identifier
in your Core Data entity. Change the name as appropriate.
With that one line of code you now have all of your existing objects in a NSDictionary
that you can then look up against as you walk the JSON.
How to Sync iPhone Core Data with web server, and then push to other devices?
I suggest carefully reading and implementing the sync strategy discussed by Dan Grover at iPhone 2009 conference, available here as a pdf document.
This is a viable solution and is not that difficult to implement (Dan implemented this in several of its applications), overlapping the solution described by Chris. For an in-depth, theoretical discussion of syncing, see the paper from Russ Cox (MIT) and William Josephson (Princeton):
File Synchronization with Vector Time Pairs
which applies equally well to core data with some obvious modifications. This provides an overall much more robust and reliable sync strategy, but requires more effort to be implemented correctly.
EDIT:
It seems that the Grover's pdf file is no longer available (broken link, March 2015). UPDATE: the link is available through the Way Back Machine here
The Objective-C framework called ZSync and developed by Marcus Zarra has been deprecated, given that iCloud finally seems to support correct core data synchronization.
sync core data with web server
Following might be helpful
http://publications.csail.mit.edu/tmp/MIT-CSAIL-TR-2005-014.pdf
http://iphone2009.crowdvine.com/talk/presentation_file/5104/Grover_Syncing.pdf
https://stackoverflow.com/a/5052208/1294448
What is the most efficient way to sync Core Data with JSON API
This could be ok, but I think you should apply the Find-or-Create pattern suggested in Apple doc. See here for a deep explanation Efficiently Importing Data (In particular see Implementing Find-or-Create Efficiently).
The overall idea is quite simple. Having two arrays of objects (the one you retrieve from Core Data and the one you retrieve from the service) that are ordered (by apiID
and id
resp.).
Obviously if there are a lot of data, I really suggest to perform operations in background. Remember that each thread needs to rely on its NSManagedObjectContext
. Otherwise take advantage of new queue mechanism provided by iOS 5 API.
For the sake of completeness, I also suggest to read RayWenderlich tutorial How To Synchronize Core Data with a Web Service Part 1 and 2. It's very interesting.
Hope that helps.
how to sync core data object to web service in objective c
If devices comes from Core Data it cannot contain NSString. Either it's NSManagedObject or NSDictionary. I guess it's NSManagedObject.
In this case it's more suitable to use the NSManagedObject as object in the loop and get the values for the nine keys respectively:
for (NSManagedObject *object in devices) {
NSSString *string1 = [object valueForKey:@"key1"];
NSSString *string2 = [object valueForKey:@"key2"];
NSSString *string3 = [object valueForKey:@"key3"];
NSSString *string4 = [object valueForKey:@"key4"];
NSSString *string5 = [object valueForKey:@"key5"];
NSSString *string6 = [object valueForKey:@"key6"];
NSSString *string7 = [object valueForKey:@"key7"];
NSSString *string8 = [object valueForKey:@"key8"];
NSSString *string9 = [object valueForKey:@"key9"];
// use the strings
//Hear call your method...It will send value one by one to web service.
}
Sync data from coredata with custom REST API when internet connection lost?
Record a transaction log when you are offline. You can capture that through the NSManagedObjectContext
API, asking it for updatedObjects
, insertedObjects
, and deletedObjects
.
Then when you get online you play back the transaction log against the server.
Sync data from Web Server to iOS App
Coming from a JavaScript background, I'll give you my answer that would work on a Cordova type mobile application running on JavaScript.
1) Create a local database on your mobile device and store all the objects in there.
2) Create a table in your database to store the "last sync" date and time.
3) Set up an API endpoint on your server to accept a "last sync" parameter and return all newer data than the last sync date and time.
4) On every page load, make a request to the API to retrieve the latest information and save it in the local database.
5) On every subsequent page loads, load the new data. (as user experience)
Now, there is a different way if you do not want to constantly make API calls on every page load.
Set up a socket connection between the mobile app and the server.
http://socket.io
This will allow you to "push" down new data everytime the server database is updated.
When a user opens up the app for the first time, make an API call to get all the updates and register on a socket.io channel for live updates.
The most crucial thing to cater for is when an API call terminates prematurely and looses some info. Only update your "last sync" date time on successful updates.
Related Topics
Avcapturevideopreviewlayer Is Not Visible on The Screenshot
How to Correctly Do Up an Adjustable Split View in Swiftui
Arkit/Realitykit - People Occlusion Config Not Working
Use of Nspathcontrol to Represent Virtual Path
Xcode 6, Swift and Mock Verification Without Exceptions
Swiftui: @Observedobject Redraws Every View
How to Pass a Class and Method to Create an Instance of a Class
How Convert a *Positive* Number into an Array of Digits in Swift
Maccatalyst App: How to Close a Window Without Terminating The App
How to Set iOS 13 Glyphs Programmatically
How to Implement a Billboard Effect (Lookat Camera) in Realitykit
Computed (Nsobject) Properties in Swiftui Don't Update The View
How to Load Nsview from Xib with Swift 3
Gmail API: How to Send Attachments to The Drafts on Swift
How to Obtain a Swift Type from a String
Swift 3 Closure Overload Resolution