Saving Data in iOS
May 31 2022 · Swift 5.5, iOS 15, Xcode 13
Part 1: Files & Data
06. Saving & Loading Data
Leave a rating/review
Notes: 06. Saving & Loading Data
This course was originally recorded in April 2020. It has been reviewed and all content and materials updated as of November 2021.
Now that you’ve learned about data types, and the relationship between data and bytes, IIt’s time to save the
In this array, I used all three types of integer literals I just went over. Everything in this column is 240, in decimal.
These are all 159:
And these are 152.
You will be able to make more sense out of what that means in the next video. For now, let’s finally save something! First, create a new instance of Data. I’ll call it
let favoriteBytesData = Data(
Helpfully, there’s an initializer that’s ready for an Array of bytes, like you have.
You need to know where this data will get stored, so create a URL constant called
favoriteBytesURL with the initializer method, which you already learned about, to have its path be within the user’s document directory.
let favoriteBytesURL = URL(fileURLWithPath: "Favorite Bytes", relativeTo: FileManager.documentsDirectoryURL)
Data has a write method that takes a URL!
As you see from the compilation error, writing will throw an error if it doesn’t succeed, so you need a “try” beforehand.
And now you know this write succeeded for two reasons.
One: you see other readouts in the sidebar down below. If an error was thrown, that wouldn’t happen in a playground. And two: you can go to the
…and see that you’ve got a file written to your document directory. How about you read it back!
To do that,
Data has an initializer that works with the contents of a URL. You’ll store the data as
let savedFavoriteBytesData = try Data(contentsOf: favoriteBytesURL)
If there’s no Data at the URL you specify, attempting to read would throw an error, so you need a
try here as well. That error could happen if your URL represented a directory, for example, instead of a file.
Note how, in the sidebar, the result that gets printed out is 16 bytes, which also coincides with the value you got in the previous video by using MemoryLayout. Excellent! To get your numbers back, you can just use the Array initializer that accepts a Data instance.
let savedFavoriteBytes = Array(savedFavoriteBytesData)
It looks right! Let’s have Swift verify that the
savedFavoriteBytes are equal to the original
favoriteBytes == savedFavoriteBytes
…They are. You can mostly treat Datas just like arrays of bytes. So, you can equate two of them directly…
favoriteBytesData == savedFavoriteBytesData
…and get the same result as equating their conversions to byte arrays.