Created
November 29, 2020 09:26
-
-
Save SlappyAUS/1564f8473c6c69c921297a0e6cb177f8 to your computer and use it in GitHub Desktop.
Property Encoder #swift #data #binary #plist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Returns the URL for the plist file that stores the drink data. | |
| private func getDataURL() throws -> URL { | |
| // Get the URL for the app's document directory. | |
| let fileManager = FileManager.default | |
| let documentDirectory = try fileManager.url(for: .documentDirectory, | |
| in: .userDomainMask, | |
| appropriateFor: nil, | |
| create: false) | |
| // Append the file name to the directory. | |
| return documentDirectory.appendingPathComponent("CoffeeTracker.plist") | |
| } | |
| private func save() { | |
| // Save as a binary plist file. | |
| let encoder = PropertyListEncoder() | |
| encoder.outputFormat = .binary | |
| let data: Data | |
| do { | |
| // Encode the currentDrinks array. | |
| data = try encoder.encode(currentDrinks) | |
| } catch { | |
| print("*** An error occurred while encoding the data: \(error.localizedDescription) ***") | |
| return | |
| } | |
| // Save the data on a background queue. | |
| background.async { [unowned self] in | |
| do { | |
| try data.write(to: self.getDataURL(), options: [.atomic]) | |
| } catch { | |
| print("*** An error occurred while saving the data: \(error.localizedDescription) ***") | |
| } | |
| } | |
| } | |
| // Begin loading the data from disk. | |
| private func load() { | |
| // Read the data from a background queue. | |
| background.async { [unowned self] in | |
| let drinks: [Drink] | |
| do { | |
| // Load the drink data. | |
| let data = try Data(contentsOf: self.getDataURL()) | |
| // Decode the data. | |
| let decoder = PropertyListDecoder() | |
| drinks = try decoder.decode([Drink].self, from: data) | |
| } catch CocoaError.fileReadNoSuchFile { | |
| print("*** No file found--creating an empty drink list. ***") | |
| drinks = [] | |
| } catch { | |
| fatalError("*** An unexpected error occurred while loading the drink list: \(error.localizedDescription) ***") | |
| } | |
| // Update the entires on the main queue | |
| DispatchQueue.main.async { [unowned self] in | |
| // Filter the drinks. | |
| self.currentDrinks = filterDrinks(drinks: drinks) | |
| // Load new data from HealthKit | |
| self.healthKitController.requestAuthorization { (success) in | |
| guard success else { | |
| print("*** Unable to authorize HealthKit. ***") | |
| return | |
| } | |
| self.healthKitController.loadNewDataFromHealthKit() | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment