AppStorage – Save Array

Archive Arrays

For a long time I thought about how I can store arrays in AppStorage. My intention was to pass an array from the app to the widgets. In the following I will present my solution. With my solution I can store String, Int, Double and even UIColor arrays.

I create a class that I assign to the NSObject and then write two functions.

class Storage: NSObject {

static func archiveStringArray(object : [String]) -> Data {
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: object, requiringSecureCoding: false)
return data
} catch {
fatalError("Can't encode data: \(error)")
}

}

static func loadStringArray(data: Data) -> [String] {
do {
guard let array = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [String] else {
return []
}
return array
} catch {
fatalError("loadWStringArray - Can't encode data: \(error)")
}
}
}

The first function helps us to archive the array, in this case the string array as pure data. The second function then returns the data as a (string) array.

Here is an example application — code example:

@AppStorage(„nameArray", store: UserDefaults(suiteName: "group.de.domain.MyApp“))
var nameArray: Data = Data()

var tempArray = ["David", "Caro", "Adrian"]

//Save Array
nameArray = Storage.archiveStringArray(object: tempArray)

Retrieve Array:

//Retrieve Array Example (SwiftUI)

ForEach(0..<{getStrings(data: entry.nameArray)).count) { i in
Text(getStrings(data: entry.nameArray)[i])

}

func getStrings(data: Data) -> [String] {
return Storage.loadStringArray(data: data)
}

First we save the temporary array in AppStorage which data is assigned to and we archive it. Then we can unpack the saved data array and call it up again as an array. In this example, we are looping through all the names.

As I said, you can’t just store a string array. Here, for example, with a UIColor array:

class Storage: NSObject {

static func archiveColorArray(object : [UIColor]) -> Data {
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: object, requiringSecureCoding: false)
return data
} catch {
fatalError("Can't encode data: \(error)")
}

}

static func loadColorArray(data: Data) -> [UIColor] {
do {
guard let array = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [UIColor] else {
return []
}
return array
} catch {
fatalError("loadWStringArray - Can't encode data: \(error)")
}
}
}

This is just a solution to store arrays in AppStorage. Of course there are several other solutions and maybe, in the next WWDC, it will be possible to store arrays more easily.

--

--

--

Swift (iOS, iPadOS & macOS) Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Flutter — my thoughts and impressions — PART V [FINAL]

Upload assets to AWS S3

Automata’s Bi-Weekly Update: Issue 20

Lean & Agile Approach For EOS Resource Model

The Medical Programmer — Why doctors should code and where you can learn today

How to centralize your log with EFK on Google Kubernetes Engine(GKE) in 10 min

f-String in Python3 for Data Scientists

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
David Koenig

David Koenig

Swift (iOS, iPadOS & macOS) Developer

More from Medium

SwiftUI | Fetch JSON data & display it into a list

User Session Management In Xamarin Forms

How to use interface for receiving JavaScript messages in swift

Generating JWT for AppStore Connect API with JWTKit in Swift