How can I ship my app with a pre-populated Core Data database? - ios

My app uses Core Data and I want some default entries to be inside.
What's best practices of how to do that?

If you're already loading the pre-load data via a temporary routine for testing in your current code there's no reason you can't use the sqlite file it creates in the simulator's directory (no need to write a separate Mac app).
If you're not already filling that db you can still write an iOS app that does it. Odds are you've already written the methods for adding data to your store so you can use them to import the pre-load data as well.
Either way you'd grab the sqlite file from the simulator's directory and add it to your app's bundle; on first launch you'll copy it into the appropriate place in the app's directory before pointing Core Data to it. If it's really large the downside is that there will be a copy in the bundle and another on disk, but there's not much you can do about that other than grabbing the data over the network.
As others have suggested, if the amount of data is small you can just import it at first launch, using the methods you've already written for adding data as part of the normal app's workflow.

See the CoreDataBooks example, which has sample code for copying a database at first launch.
EDIT: I've created a Core Data framework (read about it here: http://bikepress.org/?p=1120) that includes this feature.

I would just create a database and put add it to my target so that Xcode copies it into the app bundle. At the first launch just copy it from the app bundle to eg. the documents directory or wherever your app expects the database.

There is Core Data Editor at the app store. Alternatively you could build your own simple mac app just for this particular DB and manage it from there. If the amount of default entries is small, then you're better off storing it in a plist or something and loading it into DB after the first launch.

In iOS 5, my app was rejected if I put a database file into resource bundle. So, I have to download the database from internet instead.

Related

Enhance Resilience of Local Storage in Hybrid App

I have developed a hybrid mobile app that has been running on IOS, Android and Chrome reasonably well for over 5 years. My app uses an indexedDB database to maintain the state of the app and save it between restarts, however there are some cases where IOS can clear the indexedDB particularly if the client device is running low on memory.
I would like some help on how to maintain a parallel copy of the indexedDB using the native SQL database on the IOS device, in order to increase the resilience of my app, based on the hopeful expectation that IOS will not arbitrarily decide to clear an internal SQL database belonging to the app.
I understand how to communicate in both directions between Objective C and Javascript but I have not the foggiest idea in Objective C how to:
Create a SQL database in the app file system
Choose where to place the SQL database in the app file system
How to write a new key value pair to the database
Overwrite an existing key value pair in the database
Read back all key value pairs from the database (I expect there could be up to 1000 of these in practice) and pass these efficiently back to the javascript code.
Clear the database and start again.
Any pointers to useful resources on how to achieve this or better still coded examples would be most appreciated.
I would just like to add that I am not using Cordova or any other similar app development environment, so please do not suggest a SQLite plugin that is part of a bigger environment. I have got to where I am with a bespoke coding approach and I would like to keep it that way.
I have explored the idea of paralleling up each indexedDB save with a write to a file in the IOS App Documents Folder with the hope that this is less likely to be wiped than the Caches Folder.
Following each indexedDB setItem with a key-value-pair I pass a request to the objective-C IOS app code to create a text file in a sub folder created with the App Documents Folder, with the name 'key'.txt and the contents set to value.
Following each indexedDB removeItem, I pass a request to the objective-C IOS app code to delete the corresponding text file 'key'.txt.
Following each indexedDB clearAll, I delete the entire sub folder created above.
Now when the app starts up and discovers an empty localForage database, I pass a request to the objective-C IOS app code to test if the sub-folder with key-items is there or not.
If it is not, then this is a fresh install of the app and continue as normal for such a case.
if it is, then this is a case of the indexedDB database having been deleted.
In such case, I request the objective-C IOS app code to return the set of keys, by examining the contents of the folder created above and stripping off the .txt bit and in the case of the IOS Simulator ignoring the DS_Store file.
One by one I then request the contents of each key file and load them back into the previously empty localForage database and when this has been done I can continue as if it had not been deleted.
I found that it is necessary to use a zero duration timeout in the javascript before requesting each value to prevent call stack exceeded errors when restoring large databases.
This approach seems to work and I can test this any time by using the Safari Developer Resources tab actions to clear the database and then manually restarting the app. Using the same tab you can watch the indexedDB database being repopulated.
Due to the size of my database, I actually created a set of sub folders of different types of key, so that I could choose the order in which the database items were restored, especially as my app is often brought back to life in the background following a significant location change and in such cases there is an imposed maximum time limit on how long the app is given to do such a recovery. This refinement is of course optional and only needed for large databases.
The following notes are for anyone who wants to try this approach and assumes using Objective C in XCode 10.1
Use NSHomeDirectory() and stringByAppendingPathComponent #"Documents" to get the Documents folder.
Use stringByAppendingPathComponent to create a sub folder path for the keys sub folder.
Use fileExistsAtPath to check whether the keys sub folder exists already
Use createDirectoryAtPath if it does not.
When saving or changing items in indexedDB use the stringByAppendingPathComponent to create the key file name path e.g. Base.txt for a key of 'Base'.
Use fileHandleforWritingAtPath to get the fileHandle for a file
if fileHandle does not exist then need to create it using writeToFile to create the 'key' file
if fileHandle does exist then truncateFileAtOffseyt:0 (important) to clear it and then use writeData to create a new version of the 'key' file.
In both of the above specify UTF8 encoding.
When removing items from indexedDB do the same to get the key file path and then use removeItemAtPath.
The device can be cleared by removing the entire sub folder using removeItemAtPath.
The restore process uses contentsOfDirectoryAtPath to read the set of keys in the sub folder.
The restore process for each item uses stringWithContentsOfFile to read data files and return the contents enclosed in quotes using a call to stringByEvaluatingJavaScriptFromString
Hope this helps.

Is it safe to save persistent data as txt file for CoreData?

My iOS app uses CoreData and some tables need to be filled with default values every first time the app is opened since CoreData device-dependent.
So I am using NSUserDefaults to check whether it is first time open. If it is first time, I fill tables (on CoreData) with the values which I have already created and formatted lines from the txt file by reading line by line and separating in a way.
And my question is, is it safe and fastest way to use txt file for such operation?
A better option would be to keep a "canned" sqlite file in your app bundle and check for the existence of the SQLite file in your documents directory. If the file does not exist, copy the canned data from the app bundle to your documents directory.
That will skip the entire parsing logic and will allow your application to launch faster.
Marcus' approach is also what I would recommend. But you can still keep using your parsing code during development in order to have a convenient way to create the seed SQLite file. When you ship your app, package the newest seed store as a bundle resource and disable / delete your parsing code.

My IOS App has been rejected- Data Storage Guidelines (2.23) I have 2 possible suspects

my app has been rejected due to iCloud Storage Restrictions. (2.23).
There are lots of questions for this situation, but i am still not sure why my app has been rejected.. Here are my suspects:
1- My app downloads pdf files and images for letting users see on "offline" mode when a user selects a row from a tableview. I've set my download folder as "Documents/privateDownloads" and set the folder (and files inside) url flags as "do not backup"
2- My app also has a 2Mb. "preload.json" file, which my app reads the file at first launch and preloads into the database only at first launch (with a progress hud showing the progress of importing data). I haven't set the "preload.json" file as "do not backup".I just drag dropped the file into "Supporting Files" group in Xcode.
My guess is the problem lies in the 2nd suspect, but i've also read that i should move the "privateDownloads" folder into "Application Support" Folder instead of Documents folder.
i always stored my offline files on nsurl cache for a very long time (technically forever), but this time i've decided to do like this.
thanks for reading and helping.
Edit: there is a note from app store for rejection reason:
"In particular, we found that on launch and/or content download, your
app stores 3.6MB"
When i control this issue, this is happening after my application "preloads" the data. But what i really don't get it is, i am storing this preloaded data in core data. So yes, i want this data to be backed up in iCloud?!
To solve the issue of your seed data being too large, you might split your Core Data stack in two separate stores - one which stores the user data and is backed up to iCloud. And a second one which stores the seeded data imported from your JSON. This store could then be excluded from iCloud backup via the "do not backup"-flags.
Another recommended way would be to ship a pre-populated store like described in this article on objc.io. Since you mentioned your preload.json is several MB, this would be even more desirable to pre-generate the store once than on every device on initial app startup. And you could apply the required file attributes for not backing it up more easily.
The issue won't have anything to do with your preload.json file. If that's included in your app distribution, it is part of the app and you don't need to do anything different with it.
I would suspect that the reviewer didn't notice you were setting the 'do not backup' flag on files you've added to the Documents/privateDownloads folder, or that you have a bug and the flag isn't being set at all. It is safer, if you're able, to store those kinds of files in a /Library/Caches sub directory. Then you don't need to worry about the flag.

prepopulated static data, to ship in my iOS app

I have an app that shows static data and images, it will never update or change its content ( client's request ), The client will provide all the data, I am exploring possible ways of doing this, I've read articles close to what I am trying to accomplish that do this by
prepopulating a sqlite DB, and using coredata to load it.
Is this the best approach? This app never has to connect online to get new data or updates, just show whatever it contains locally.
Thanks.
That should work. Use core data, build the app in the simulator. Then go into the simulator folder, copy the sqlite into the app and link to it in the app delegate. At that point it will ship with the app.
For images you should store in your app's folder as opposed to putting in core data, then put the url to the image or document in your entity (if you need it). Use NSFileManager to store docs and images in your app's folder.

Core data solution for read-write separate

I am doing something with core data. Since the original sqlite file contains the data in the application. I decide to do the following:
Separate the reading and writing action. Make all the reading from one data source of one sqlite file and make all the writing in another file.
Since there are some rules in the directory in iOS application, I plan to copy all the reading data from bundle to the cache directory and put the writing data in the document directory.
The question is that, is it possible to use the reading file in the bundle resource directly. Which means I don't have to copy it into the cache file and that will save some space for the device.
Or you guys have any other better idea, please tell me.
I put the write data into the document because the file in it can be backuped by icloud, which could act as a feature in my program.
You ask if what you want to do is a good idea, but first you need to think through some possible pitfalls.
I suppose the file in your bundle was also created with Core Data, and it has a MOM. The new file you write - it probably uses the same MOM. What will you do if you ever need to update the MOM? The file on iCloud will be say version 1, and maybe the users iPhone uses Version 1, but your new version 2 is loaded onto the users iPad. Now what? The ipad should not update the repository as that would make the iPhone fail when it tries to use the data - the ipad has no way of knowing if all other devices have updated or not.

Resources