How to store json file locally for quick access - ios

Is there any way I can download json file from webserver and store it in a local folder for easy access for those with poor internet connection, so data will be downloaded once and user won't have to suffer every time.
I found similar questions on here1 and here2, but they were asked for objective-C, but I was looking something for Swift. Thanks

Yes, you can certainly do this. After you've read the remote JSON, it will be a Data object.1
Build a URL to a path in your app's caches directory and then use the Data method write(to:options:) to write that data into your file.
On read, check to see if the file exists in the caches directory before triggering a network read. Note that you need to be sure that the filenames you use are consistent and unique. (The same filename must always fetch the same unique data.)
1 Note that Mohammad has a good point. There are better ways of persisting your data than saving the raw JSON. Core Data is a pretty complex framework with a steep learning curve, but there are other options as well. You might look at conforming to the Codable protocol, which would let you serialize/deserialize your data objects in a variety of formats including JSON, property lists, and (shudder) XML.

Yes, you can create a .json file and store it in documents folder. First see how to create .json file, and then see how to store a file in documents folder.
Check this

Related

What's the best way to store a JSON file with complex data structure for later use?

So I have an iOS app and this JSON file (about 50 MB) that has a deep tree structure. The goal is to store this file locally and use its content later on the app, with the possibility of updating the data or some parts of it in the future..
After some research, I found out that I can use core data, but it seems inconvenient for such complex structure.
So, I thought maybe I'll persist the data in a class object, but this may end up consuming the whole mobile memory.
Now, I'm thinking if it is plausible to store the data in a plist then map the hell out of it to present its content.
What do you think guys? Do you have any other ideas or thoughts?
Just store the JSON as you received it, as NSData. It doesn't care one bit about the structure, so you can parse it again.
After a lot of research and reflexion, I ended up using Realm for its simplicity and effectiveness.

Advise where to store data for iOS app

I have created an app using ionic and cordova and now I want to remake it on iOS. I am working with iOS for the first time, and I cannot figure out how to store data.
For example: I have a form where user has to input some data, but the inputs are not in one view, there must be several views. I used to create empty array and just put everything step by step, but now i can't use same view controller on multiple views. Tried to do it with core data, but core data cannot store arrays. My object would look something like this:
var sampleArray = (
duration: 13,
dayOfTheWeek: Thursday,
personList: [
(name: Rocky,
age: 26),
(name: Ralph,
age:23)
]
)
The question would be: How could I make an input form which would be on several views and where should I store the data, and later I would be able to store all the data into core data?
You can work with persistent data in several ways on iOS.
User Default
This is a tool that is used to store small amounts of information like user settings, preferences etc. Don't use it for data that will scale with application usage (e.g. like notes in notepad app). Documentation will answer all your questions about User Defaults.
Database
You have Core Data as an out of the box solution which is build on top of the SQLite and takes some time to learn, but from my experience it's worth the effort. You are free to use pure SQLite or other database type, but it requires more code and probably custom frameworks.
Text files
You can use arbitrary XML, JSON or CSV files to store your data. Tooling is rich (e.g. NSXMLParser or SwifyJSON just to name two) and if you look on Github, you will find what you need. You can also use build in combination of NSCoder and NSKeyArchiver / NSKeyUnarchiver which are easy to grasp.
Binary files
Finally, for a local storage you can use binary files i.e. images. This is too advanced topic to cover here, but I want to share an example of Open Raster file format. It is used to save informations for drawing apps (eq. GIMP) and inside, it is basically an XML file and a bunch of images compressed to zip and named as .ora file. Creating your own specification for a hybrid format is not that hard.
Network repository
Just to not overlook other methods, you can use remote database API to store data outside of the device, but of course you need your own host and some backend skills.
I hope I didn't miss something important. I just wanted to sum up this knowledge in one place for future reference.
As the first comment says, your question is quite large.
When you say 'one form on several view', I consider it as 'one form per view'.
Keep It Simple S... ;)
(Except if you use page control for your form.)
Basically, you have three ways to store data :
NSUserDefaults :
Store data in Dictionary for later use
File :
Save data to a File (why not .csv like ?)
CoreData :
You can persist arrays as binary data in Core Data
There are numerous tutorials on these topics.
www.raywenderlich.com site is a good one to begin...

Using a .txt file to store data in iOS?

I am making a few apps that all require pre-set data to be loaded into the app. This data does not need to be changed or altered in any way as the app progresses - it is simply the data that the app runs on (to give more detail, it is questions for a quiz app). I have elected to use .txt files to store this data, but I wanted to know if this is the best way to do this? Text files allow me to easily change the data without coding. I can also copy and paste from normal documents. Is storing data in this way a good practice, or should I try to hard-code the data/ use a p-list?
The answer to this question depends a lot on how you want to implement your code.
.TXT files might work well, but what happens to the memory requirements when you pass a certain number of questions (e.g. more than 100, or even 10?). Also, what kind of structure are you using in memory to hold the question? If it's a NSDictionary or NSArray, perhaps a .plist file might work better for you.
Raw NSData, or some proprietary format, might work best if you have a lot of non-modifiable questions and you want to try to compress the data down as much as possible (which is a consideration on the low memory / low disk space iPhones).
CoreData might come in handy if you want to store a lot of questions and answers, especially those that users are manually entering in or managing.
For something like this, I will typically use JSON files, and then use Apple's JSON parsing framework.

NSCoder + UIDocument: are they compatible?

This is probably a naive question - but I want to double check to avoid wasting time with UIDocument if it doesn't do what I want.
Background: I have an app for which I have created a simple file system to save out user created documents as plists. I have my encoding/decoding all working. I am using some primitive types and handle that with the appropriate encoder method. I have a naming system and save the plists to a custom directory in the Library directory since these are docs the user should not have direct access to. (they can export their data to the documents directory if they so choose.
I started thinking about "autosave" and then discovered UIDocument - looks pretty great.
So given the above, does it seem like I can use UIDocument? What I save out is a custom class "Project" instance derived from NSObject. It contains a bunch of NSMutable arrays which contain instances of custom classes, NSDictionaries etc. I'm going through this UIDocument tutorial now: http://www.raywenderlich.com/6015/beginning-icloud-in-ios-5-tutorial-part-1 but don't want to discover that it's not going to work because of my data, etc.
Update:(for those reading along at home... ;-) Made some progress with this.
UIDocument uses NSKeyedArchiver rather than NSCoder (Wrong - see answer below) but the encoding method names are the same so it was easy to adjust what I already had.
Have been able to save out a plist that looks like it is capturing all the data - but I won't know until I try to read it all back in. Getting an error that I haven't sorted out:
NSFileCoordinator: A surprising server error was signaled. Details: Connection invalid
Not so surprising since I am saving locally not clear why it is trying to connect to iCloud at all. Hopefully I can switch that off.
I'm not sure where you get the thing about UIDocument using NSKeyedArchiver. For a simple implementation all you need to do is provide an NSData representation of your document contents -- it doesnt matter whether you generate that data from your model objects with NSCoder, NSKeyedArchiver, NSPropertyListSerialization, or some custom scheme.
Given that, I don't see any reason it shouldn't work with the data model you describe.

Initialize Core Data With Default Data

I have a basic question regarding populating Core Data with data. I am building an application, which will show ATMs on a map. I would like to ship the application with a preloaded database, but to give users the option to receive updates when they launch the app. I am thinking about using a property list for the update. Basically send a plist of all the ATMs, parse that plist and populate the sqlite. I will have around 7000 entries in the property list file, each entry containing 5-6 keys with short string values. But according to the Apple iOS Developer Library:
You can create a property list—or some other file-based
representation—of the data, and store it as an application resource.
When you want to use it, you must open the file and parse the
representation to create managed objects. You should not use this
technique on iOS, and only if absolutely necessary on Mac OS X.
Parsing a file to create a store incurs unnecessary overhead. It is
much better to create a Core Data store yourself offline and use it
directly in your application.
Should I still be sending a property list or rather think for an alternative solution to update the application's database?
P.S. I am thinking about using a Rails app for providing updates - basically sending a plist file.
I had nearly the same question a few months back, did quite a bit of searching to find a nice easy answer, failed to find it and eventually settled on a roll-your-own solution that took a bit more time than I would have hoped, but was at least very helpful in learning to understand Core Data.
Basically the solution was to write a little utility that parsed my source data (which for me is a comma-separated text file, parsed using the quite handy 'cCSVParse' library - http://michael.stapelberg.de/cCSVParse ) and inserted it into Core Data Managed Objects and then saved that off as a sqlite persistent store. Then the sqlite store(s) can be shipped with the app, and uploaded by the user when they buy more data.
You could write a conversion from plist (or whatever) into the core data representation within the app itself, but if the data is just going live out the rest of its days in some core data form, why not let your beefy dev box do the heavy lifting before you send the data to the user, instead of shipping the data to the phone and making it do the work?

Resources