![]() There are two things you can’t see in that code, but both matter. Go ahead and give the app a try and see what you think – you ought to be able tap the button a few times, go back to Xcode, run the app again, and see the number exactly where you left it. Notice how that uses exactly the same key name, which ensures it reads the same integer value. Speaking of reading the data back, rather than start with tapCount set to 0 we should instead make it read the value back from UserDefaults like this: private var tapCount = (forKey: "Tap") This key is case-sensitive, just like regular Swift strings, and it’s important – we need to use the same key to read the data back out of UserDefaults. We attach a string name to this data, in our case it’s the key “Tap”.There is a single set() method that accepts any kind of data – integers, Booleans, strings, and more.For example, if you want to share defaults across several app extensions you might create your own UserDefaults instance. This is the built-in instance of UserDefaults that is attached to our app, but in more advanced apps you can create your own instances. In just that single line of code you can see three things in action: So, add this after the tapCount += 1 line: (tapCount, forKey: "Tap") ![]() To make that happen, we need to write to UserDefaults inside our button’s action closure. ![]() Here’s a view with a button that shows a tap count, and increments that count every time the button is tapped: struct ContentView: View private var tapCount = 0Īs this is clearly A Very Important App, we want to save the number of taps that the user made, so when they come back to the app in the future they can pick up where they left off. Even better, SwiftUI can often wrap up UserDefaults inside a nice and simple property wrapper called – it only supports a subset of functionality right now, but it can be really helpful.Įnough chat – let’s look at some code. UserDefaults is perfect for storing things like when the user last launched the app, which news story they last read, or other passively collected information. Tip: If you’re thinking “512KB? How much is that?” then let me give you a rough estimate: it’s about as much text as all the chapters you’ve read in this book so far. To give you at least an idea, you should aim to store no more than 512KB in there. There is no specific number attached to “a small amount”, but everything you store in UserDefaults will automatically be loaded when your app launches – if you store a lot in there your app launch will slow down. One common way to store a small amount of data is called UserDefaults, and it’s great for simple user preferences. Most users pretty much expect apps to store their data so they can create more customized experiences, and as such it’s no surprise that iOS gives us several ways to read and write user data.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |