Save Program State In Swift UI

To Save Program State in SwiftUI the data you are trying to save must conform to the Codable Type. (How To Conform To Codable Protocol)

In order to save a file we will use the JSONEncoder to encode our programs state and write it to a json file.

func save() {
        let url = getDocumentsDirectory().appendingPathComponent("data.json")
        let data = try? JSONEncoder().encode(players)
        let string = String(data: data!, encoding: String.Encoding.utf8)
        do {
                try? string!.write(to: url,
                                     atomically: true,
                                     encoding: .utf8)
            }
    }

To load a File we’re going to load in the Data from the url, return if the file is empty or doesn’t exist, and then use the JSONDecoder to decode into our class.

 func load() {
        let url = getDocumentsDirectory().appendingPathComponent("data.json")
        let data = try? Data(contentsOf: url)
        if data == nil {
            print("File empty")
            return
        }
        let players = try? JSONDecoder().decode([Player].self,from: data!)
        self.players = players!
        
    }

The last thing we need to do is save our state and load our state. For my purposes I wanted to save the state whenever the app closed or went to the background. To do this attach the following instance method to the parent view:

.onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)){ _ in
save()
}

To load the file we’ll attach the onAppear instance method:

.onAppear(perform:{load()})

Contact

Content is copyrighted 2019-2023 © D.S. Chapman. This site was built using GatsbyJS. Code for this website is open source and available on Github