Best solution for storing JSON data in iPhone - ios

I am working on developing a civic engagement app that provides information on bills making their way through a particular state house. The API I am using updates every hour, if a user accesses the information within that hour, I would like to archive the most recent JSON data on their phone (and update it on the hour as well). What is the best solution for storing JSON data? Core Data, NSCoding, or UserDefaults

Core Data will be the best option to cache your data locally. UserDefaults is least recommendable as if any particular value, corresponding to the key you are trying to save, comes Nil, Your application will crash.

The most simple way is to save Serialization data as plist file:
let plistData = try PropertyListSerialization.data(fromPropertyList: jsonDict, format: .xml, options: PropertyListSerialization.WriteOptions(0))
try plistData.write(to: urlToLocalFile, options: .atomic)
And then read this file:
if let dictionary = NSDictionary(contentsOf: urlToLocalFile) {
//do something with dictionary
}

Related

What is correct way to store/retrieve user data (read/write files) in iPhone (iOS) dev via Swift?

Background
I've written one particular app via Windows Forms (C#), Android (Java and Kotlin), HTML5 Web App, ElectronJS (runs on Linux, Mac, and Win10) and even as a UWP (Universal Windows Platform) app.
All Use JSON File For Data
All of those apps use the exact same JSON formatted data for user settings.
That means I can share data on all platforms via the same file and file format.
On Android there is the additional benefit of having the file saved in the UserPrefs (which provides security and backup for user).
The Problem
I've also written the app as an iPhone/iPad app (Swift), however I cannot find the proper way to handle the JSON file storage.
The problem is not related to de-serializing the JSON into my business object. That all works fine. However, I am not sure about:
where should files be stored in the iPhone/iPad system?
can you save a file in some sort of user preference or appdata
location?
How do you open a file for read/write and read/write data? (Swift)
How can I better understand the paths available to read and write
files?
I've searched all over looking for this answer. Can you point me to official documentation, a book, a StackOverflow item or something that explains this clearly? (Hopefully with Swift examples.)
See iOS Storage Best Practices video and the File System Basics document. That should get you going.
In short, app data is generally stored in “application support directory”, documents exposed to the user (e.g. the Files app) are stored in “documents” folder, downloads that can be easily re-retrieved are stored in “caches” folder. Technically you could use UserDefaults for storing of this sort of application data, but it really is not intended for this purpose.
Re opening a file for “read/write”, when dealing with JSON, you don’t generally do that. You read the file into a Data and deserialize the JSON into your model objects.
do {
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("appdata.json")
let data = try Data(contentsOf: fileURL)
let appData = try JSONDecoder().decode(AppData.self, from: data)
// do something with appData
} catch {
print(error)
}
When you want to update, you serialize the model objects into a Data containing your JSON and then write it to the file, replacing the file.
do {
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("appdata.json")
let data = try JSONEncoder().encode(appData)
try data.write(to: fileURL)
} catch {
print(error)
}
Obviously, this assumes that the AppData type (or whatever you call it) conforms to Codable, but you said you were familiar with serialization of JSON. See Encoding and Decoding Custom Types for more information.

Background Seeding/Loading iOS Core Data Store

My iOS 8.0 + app is essentially a dictionary app, presenting a read-only data set to the user in an indexed, easily navigable format. I have explored several strategies for loading the static data, and I have decided to ship the app with several JSON data files that are serialized and loaded into a Core Data store once when the app is first opened. The call to managedObjectContext.save(), therefore, will happen only once in the lifetime of the app, on first use.
From reading Apple's Core Data Programming Guide in the Mac Developer Library (updated Sept. 2015), I understand that Apple's recommended practice is to 1) separate the Core Data stack from the AppDelegate into a dedicated DataController object (which makes it seem odd that even in Xcode 7.2 the Core Data stack is still put in the AppDelegate by default, but anyway...); and
2) open (and, I assume, seed/load) the persistent store in a background thread with a dispatch_async block, like so :
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
//(get URL to persistent store here)
do {
try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
//presumably load the store from serialized JSON files here?
} catch { fatalError("Error migrating store: \(error)") }
}
I'm just getting started learning about concurrency and GCD, so my questions are basic:
1) If the data set is being loaded in a background thread, which could take some non-trivial time to complete, how does the initial view controller know when the data is finished loading so that it can fetch data from the ManagedObjectContext to display in a UITableView ?
2) Along similar lines, if I would like to test the completely loaded data set by running some fetches and printing debug text to the console, how will I know when the background process is finished and it's safe to start querying?
Thanks!
p.s. I am developing in swift, so any swift-specific tips would be tremendous.
Instead of trying to make your app import the read-only data on first launch (forcing the user to wait while the data is imported), you can import the data yourself, then add the read-only .sqlite file and data model to your app target, to be copied to the app bundle.
For the import, specify that the persistent store should use the rollback journaling option, since write-ahead logging is not recommended for read-only stores:
let importStoreOptions: [NSObject: AnyObject] = [
NSSQLitePragmasOption: ["journal_mode": "DELETE"],]
In the actual app, also specify that the bundled persistent store should use the read-only option:
let readOnlyStoreOptions: [NSObject: AnyObject] = [
NSReadOnlyPersistentStoreOption: true,
NSSQLitePragmasOption: ["journal_mode": "DELETE"],]
Since the bundled persistent store is read-only, it can be accessed directly from the app bundle, and would not even need to be copied from the bundle to a user directory.
Leaving aside whether loading a JSON at the first startup is the best option and that this question is four years old, the solution to your two questions is probably using notifications. They work from all threads and every listening class instance will be notified. Plus, you only need to add two lines:
The listener (your view controller or test class for question 2) needs to listen for notifications of a specific notification name:
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.handleMySeedNotification(_:)), name: "com.yourwebsite.MyCustomSeedNotificationName", object: nil)
where #objc func handleMySeedNotification(_ notification: Notification) is the function where you are going to implement whatever should happen when a notification is received.
The caller (your database logic) the sends the notification on successful data import. This looks like this:
NotificationCenter.default.post(name: "com.yourwebsite.MyCustomSeedNotificationName", object: nil)
This is enough. I personally like to use an extension to Notification.Name in order to access the names faster and to prevent typos. This is optional, but works like this:
extension Notification.Name {
static let MyCustomName1 = Notification.Name("com.yourwebsite.MyCustomSeedNotificationName1")
static let MyCustomName2 = Notification.Name("CustomNotificationName2")
}
Using them now becomes as easy as this: NotificationCenter.default.post(name: .MyCustomSeedNotificationName1, object: nil) and even has code-completion after typing the dot!

Cloudkit fetch data (strings and image asset) take a long time to appear after call

I was hoping that someone can help a coding newbie with what might be considered a stupid question. I'm making a blog type app for a community organization and it's pretty basic. It'll have tabs where each tab may be weekly updates, a table view with past updates and a tab with general information.
I setup cloudkit to store strings and pictures, and then created a fetchData method to query cloud kit. In terms of the code (sample below) it works and gets the data/picture. My problem is that it takes almost 5-10 seconds before the text and image update when I run the app. I'm wondering if that's normal, and I should just add an activity overlay for 10 seconds, or is there a way to decrease the time it takes to update.
override func viewDidLoad() {
fetchUpcoming()
}
func fetchUpcoming() {
let container = CKContainer.defaultContainer()
let publicData = container.publicCloudDatabase
let query = CKQuery(recordType: "Upcoming", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
publicData.performQuery(query, inZoneWithID: nil) { results, error in
if error == nil { // There is no error
println(results)
for entry in results {
self.articleTitle.text = entry["Title"] as? String
self.articleBody.text = entry["Description"] as? String
let imageAsset: CKAsset = entry["CoverPhoto"] as! CKAsset
self.articlePicture.image = UIImage(contentsOfFile: imageAsset.fileURL.path!)
self.articleBody.sizeToFit()
self.articleBody.textAlignment = NSTextAlignment.Justified
self.articleTitle.adjustsFontSizeToFitWidth = true
}
}
else {
println(error)
}
}
}
Another question I had is about string content being stored on cloud kit. If I want to add multiple paragraphs to a blood entry (for example), is there a way to put it in one record, or do I have to separate the blog entry content into separate paragraphs? I may be mistaken but it seems like CloudKit records don't recognize line breaks. If you can help answer my questions, I'd be really appreciative.
It looks like you might be issuing a query after creating the data, which isn't necessary. When you save data, as soon as your completion block succeeds (with no errors) then you can be sure the data is stored on the server and you can go ahead and render it to the user.
For example, let's say you're using a CKModifyRecordsOperation to save the data and you assign a block of code to the modifyRecordsCompletionBlock property. As soon as that block runs and no errors are passed in, then you can render your data and images to your user. You have the data (strings, images, etc.) locally because you just sent them to the server, so there's no need to go request them again.
This provides a quicker experience for the user and reduces the amount of network requests and battery you're using on their device.
If you are just issuing normal queries when your app boots up, then that amount of time does seem long but there can be a lot of factors: your local network, the size of the image you're downloading, etc. so it's hard to say without more information.
Regarding the storage of paragraphs of text, you should consider using a CKAsset. Here is a quote from the CKRecord's documentation about string data:
Use strings to store relatively small amounts of text. Although
strings themselves can be any length, you should use an asset to store
large amounts of text.
You'll need to make sure you're properly storing and rendering line break characters between the user input and what you send to CloudKit.

How to pass Core Data objectID and use it with Continuity

Just trying to update some Core Data apps with Continuity and have run into a bit of an issue with using the selected objects ID in the userInfo dictionary to display the correct data on the continuing device.
My first thought was to use the ObjectID, however on the receiving device this would never find a corresponding object in the Core Data store.
As it turns out the URL representation of the objectID contains the UUID of the store itself, and because the two stores UUID's are different this is obviously going to fail.
So I guess I could replace the Core Data store's UUID in the URL with the continuing devices UUID and use this, and no doubt it would work.
The Url seems to be of the following format
Does anyone know what the correct way would be to pass a reference to an object between two devices with core data stores that are synchronised via iCloud?
I'll answer this one myself and see if there are any better answers...
I pass the url of the objectID (from objectID.URIRepresentation) using Continuity API and on the receiving device create a new URL using the following:
url is the url passed in the NSUserActivity.userInfo dictionary
let storeUUID = self.identifierForStore()
// Switch the host component to be the local storeUUID
let newURL = NSURL(scheme: url.scheme!, host: storeUUID, path: url.path!)
func identifierForStore()->NSString? {
if let store = self.persistentStoreCoordinator?.persistentStores[0] as? NSPersistentStore {
return store.identifier
} else {
return nil
}
}
This seems to work just fine - hope it helps someone

NSArray to NSData encoding formatting

I am putting together a program that reads the sensors within a cell phone and saves the sensor data to a core-data SQLite model, with each set of readings pertaining to a particular session
The program provides the user with the option to email a .csv file of a particular session.
Having never done this before, I approached the issue by initializing a delegate and context, and searching the core data for entities that pertain to a specified session. The entities that satisfy the session attribute then have their data fields (gps, mag, accel, gyro) read and put into a string. Then the string is appended to an array. All done in swift.
After the entities are searched and the array is created, I attempt to create a csv file for attachment to an email. The file is attached successfully, but my encoding technique is presenting additional data prepended and appended to the file.
I want to save a file on the phone and email a copy to the user.
Here is what I have to change the Array to NSArray before converting again to NSData:
let paths: NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true);
let path = paths[0].stringByAppendingPathComponent("SessionData.csv")
if !NSFileManager.defaultManager().fileExistsAtPath(path)
{
NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil)
}
else
{
NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil)
}
var handle: NSFileHandle = NSFileHandle(forWritingAtPath: path)
handle.truncateFileAtOffset(handle.seekToEndOfFile())
var arrayToWriteNS = (arrayToWrite as NSArray)
var dataNS: NSData = NSKeyedArchiver.archivedDataWithRootObject(arrayToWrite as NSArray)
handle.writeData(dataNS)
mc.setSubject(emailTitle)
mc.addAttachmentData(dataNS, mimeType: "text/csv", fileName: "SessionData.csv")
Here is the prepended and appended data:
bplist00‘()T$topX$objectsX$versionY$archiver—TrootĨ
!U$null“
V$classZNS.objectsÄ©ÄÄÄÄÄÄÄÄ Ä
"My Data"
“"#$'X$classesZ$classname¢%&WNSArrayXNSObjectWNSArray܆_NSKeyedArchiver(25:<IOT[fhrtvxz|~ÄÇÑ·Ø}KÁµÉQV_jmu~Üã*ù
In a large data session with 28,000 entities there may be ~750 lines of prepended data.
Any help that you can provide would be appreciated.
I'm new to iOS, Obj-C, and swift, thus I'm positive there is a better way to do this, I just haven't discovered a better method yet.
Thank you.
UPDATE: Ended up just using the NSString data encoding and writing to my file in increments:
handle.truncateFileAtOffset(handle.seekToEndOfFile())
var stringToWriteNS = (stringToWrite as NSString).dataUsingEncoding(NSUTF8StringEncoding)
handle.writeData(stringToWriteNS!)
You do not want NSKeyedArchiver, it is for archiving and restoring classes.
You need to go through the array and create a text representation of each item in a format you what to present to the user.
A quick search of CocoaPods reveals several projects that may fit you needs to generate csv format data.
This one might be what you need.
csv is fairly simple so it would be reasonable to format your data to csv by writing your own code.

Resources