How to save local data in a Swift app?
The simplest solution for storing a few strings or common types is UserDefaults.
The UserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Boolean values, and URLs.
UserDefaults
lets us store objects against a key of our choice, It's a good idea to store these keys somewhere accessible so we can reuse them.
Keys
struct DefaultsKeys {
static let keyOne = "firstStringKey"
static let keyTwo = "secondStringKey"
}
Setting
let defaults = UserDefaults.standard
defaults.set("Some String Value", forKey: DefaultsKeys.keyOne)
defaults.set("Another String Value", forKey: DefaultsKeys.keyTwo)
Getting
let defaults = UserDefaults.standard
if let stringOne = defaults.string(forKey: DefaultsKeys.keyOne) {
print(stringOne) // Some String Value
}
if let stringTwo = defaults.string(forKey: DefaultsKeys.keyTwo) {
print(stringTwo) // Another String Value
}
Swift 2.0
In Swift 2.0 UserDefaults
was called NSUserDefaults
and the setters and getters were named slightly differently:
Setting
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("Some String Value", forKey: DefaultsKeys.keyOne)
defaults.setObject("Another String Value", forKey: DefaultsKeys.keyTwo)
Getting
let defaults = NSUserDefaults.standardUserDefaults()
if let stringOne = defaults.stringForKey(DefaultsKeys.keyOne) {
print(stringOne) // Some String Value
}
if let stringTwo = defaults.stringForKey(DefaultsKeys.keyTwo) {
print(stringTwo) // Another String Value
}
For anything more serious than minor config you should consider using a more robust persistent store:
- CoreData
- Realm
- SQLite
Best method to store data for an iOS app?
If the data you want to store is very little and not sensitive, you can use UserDefaults
For example, user's name, their age etc.
For Large amounts of data you should use Core Data, its a good and an easy way to manage your objects. For example, you have 1000 items, each with a property, you can basically use core data for that. It is pretty straightforward as how to create Managed Objects, store them and how to later retrieve them using queries.
Basically when you configure your project with core data, project creates an sqlite file attached to your project.
There are many tutorials on how to get started with Core Data, if you have an average experience with iOS, it will be a piece of cake for ya.
Here's a nice tutorial that will help you setup core data in your project:
https://www.raywenderlich.com/173972/getting-started-with-core-data-tutorial-2
Saving data locally (IOS)
You have a number of options to save your app's data.
Which storage option you choose, depends on a number of factors, such as a the volume of data plan to store, performance expectations, how complex your data structure is, Do you plan to sync the data across devices (For eg: Same user installs app on an iPhone & iPad), Security considerations etc.
Bear in mind it's impossible to give an exhaustive list. Here are a few basic options.
Storage Option 1 :
Data that is stored locally on the device.
- Use Userdefaults - quick and easy, but not recommended.
- Store data in a file on the device. - Check out iOS Documents on serialisation.
- Core Data - Use this, If you expect to have a large amount of data, with complex data structure.
- Other databases, like SQLite. Check out FMDB.
Storage Option 2 :
If you plan to access the data from other locations, (another device, web app etc).
- iCloud - Apple's cloud storage solution.
- Firebase
- Tons of other third party storage as a service options.
What is the best way to store / load local data in iOS?
I know that your structure is more complicated, but I wanted to tackle the multiple arrays question. Consider something like:
let teachers = ["Larry Fine", "Curly Howard", "Moe Howard"]
let classNames = ["Calculus 101", "Religious Studies 102", "Teaching with Technology in Film and Media Studies 201"]
Rather than having multiple arrays, you might have a single structure, e.g.:
struct Course: Codable {
let teacher: String
let className: String
}
You could then represent that in a single JSON structure in a text file, say courses.json
, like so:
[
{
"teacher" : "Larry Fine",
"className" : "Calculus 101"
},
{
"teacher" : "Curly Howard",
"className" : "Religious Studies 102"
},
{
"teacher" : "Moe Howard",
"className" : "Teaching with Technology in Film and Media Studies 201"
}
]
In Swift 4, you'd do something like:
var courses: [Course]?
And then to load a JSON file from your bundle and populate courses
:
let fileURL = Bundle.main.url(forResource: "courses", withExtension: "json")!
let data = try! Data(contentsOf: fileURL)
courses = try! JSONDecoder().decode([Course].self, from: data)
You then end up with a single array of courses which has advantages over the separate teachers
and courseNames
arrays. For example, if you want to sort the courses by course name, it makes sure that the course name and teacher name are sorted together.
Now, I know your structure is more complicated than this, so your JSON is likely to get more complicated, too, but I just wanted to illustrate the idea of (a) custom objects; and (b) using Swift 4's new Codable
protocol and JSONDecoder
to parse that JSON.
Saving data throughout multiple app launches
Just have a variable that's a boolean that is based on the switch. Then use UserDefaults to store the data.
var audioDisabled = true
UserDefaults.standard.set(audioDisabled, forKey: "audioDisabled")
The variable in the code above is based on whether the user has the audio on or off. I then set it to storage through UserDefaults, which will hold values even after the app is closed. The key will be how you will have access to the stored value.
If you want to retrieve that data when the user opens the app, use
audioDisabled = UserDefaults.standard.object(forKey: "audioDisabled") as? Bool ?? true
You can also do false after the ?? if the default option is no audio. I just set the default to true if the user went to the setting and configured the audio setting
In here, I'm using the value using the key that I set above. I'm telling the program that if the stored value exist, it will be in the form of a Bool and if not, then audioDisabled
will be set to true
I hope that helps
Best Way to save data locally on the device in iOS app
It sounds as though the text field (with the 1000-2000 words) is static text that is bundled with the app and can not be changed by the user of the app. If that's the case, then you can store that data in the app bundle with plist files, or JSON files and load it on demand (assuming you don't need to search though it).
Then, if each of those records has only a single boolean
value that is changeable by the user, those could be stored in NSUserDefaults
very easily (since you've stated you're only dealing with 35-40 records). You'd use the id
to link the boolean
to the data file.
You could use Core Data
or Realm
to store the data, but it may be overkill if you don't need a search feature and the user can't change the text. But if you do go with a database option, be aware that you can not store static data (the text), in a location that is backed up by iCloud, or Apple will reject your app. Regardless of whether you use iCloud in the app or not. So if you were to create a Core Data
persistent store and save it to the users Documents
folder, then load in all the static data, you will be rejected. You would want to save that data store in the users Cache
folder so that iCloud doesn't back it up. The issue you'll hit after that though is that you want the user's choices that are your boolean
values backed up. This means they need to be stored in a different place. Core Data
does have a feature that lets you create Configurations
where it will separate the user changeable data from the non-changeable data, but again, that's overkill for your case.
I'd recommend starting with Realm
over 'Core Data` for such a small dataset. It's much easier to get up and running.
How to save and store data locally and on a server simultaneously in Swift?
Since you're already looking into Firebase, I'd suggest leveraging their Realtime Database tool, as it handles everything from automatically syncing data between client and server, and leverages offline databases in case your users go offline and they have SDKs for iOS and Android.
Related Topics
How to Detect If App Is Being Built For Device or Simulator in Swift
Enabling Auto Layout in iOS 6 While Remaining Backwards Compatible With iOS 5
How Does View Controller Containment Work in iOS 5
Are There APIs For Custom Vibrations in Ios
How to Recognize Swipe in All 4 Directions
iOS (Iphone, iPad, Ipodtouch) View Real-Time Console Log Terminal
Xcode 6 - Xcassets For Universal Image Support
How to Add Objects to a Uiscrollview That Extend Beyond Uiview from Storyboard
How to Take a Full Screen Screenshot in Swift
How to Compress/Resize Image on iOS Before Uploading to a Server
Reason: No Suitable Image Found
Detecting Color of Iphone/Ipad/Ipod Touch
Run Code Only After Asynchronous Function Finishes Executing
Xcode 6: Keyboard Does Not Show Up in Simulator
Swift 3.1 Deprecates Initialize(). How to Achieve the Same Thing