Hi
It has been 4 days for me researching, reading, studying and trying to find a solution for this issue or at least Similar, that I am facing or better said I was facing ...
My issue:
I have an application that is already on production and it uses only CoreData, I wanted to go to the next step and include CloudKit to the app, so the user can use it on multiple devices or even after they delete the app they can see and check their old process, I wanted to sustain the data the user saved for them.
I changed the NSPersistentContainer to NSPersistentCloudContainer, added the needed Capabilities, sat the merge policy and assigned the automaticallyMergesChangesFromParent to true.
during testing the app started and everything did migrate I can see it on the dashboard.
the issue was every time I install the app on a different device I never got the entries fetched from iCloud though I can see for that particular user there are entries in my Dashboard.
so the app would generate new entries and sync them to cloud, then after I run the app on that device again, I get the old entries and the new ones that were just added.
How I solved it:
The Idea, the iCloud somehow for the first run is not really synced so I added a function that force sync the cloud before the app starts (in sceneDelegate scene willConnectTo or AppDelegate didFinishLaunchingWithOptions)
what the function does.
I first initialise a CKContainer and get hold of the privateCloudDatabase , as per default the NSPersistentCloudContainer uses the private cloud to save data, unless told otherwise.
then I make a CKQuery to get hold of entries that are in the cloud if there are some.
if I got to know that there are entries in the cloud:
I save a flag to inform later my VM in my VC that yes there are entries in the cloud or there are not.
I initialise a dummy entry save it to my context and then directly delete it (there I made sure that the sync has happened).
this method is an asynchronous/await function, so I wait for it before I start the app.
after this the app starts and I have the information I need to either start the app with really new entries (so I initiate the new entries and sync them) or if the user have a newly installed app but used before I inform the user with an alert asking them to either start the app as a fresh start or migrate the iCloud content to the new app. if the user selects to indeed migrate, then I start the fetch process and I get all the old entries from iCloud.
So What I did is to make sure there is a hand-shake happening to the Cloud.
I hope this helps all who are facing similar issues.
Cheers,
Mohd
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags: