Created
October 17, 2019 16:14
-
-
Save PetreVane/b7429b6847d976ab03f10802cd00ffd0 to your computer and use it in GitHub Desktop.
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
// Decoding User Info | |
func decodeUserInfo(from data: Data) -> Result<User, Failure> { | |
let decoder = JSONDecoder() | |
let decodedData = try? decoder.decode(DecodedUserInfo.self, from: data) | |
guard let userData = decodedData?.person else { print("Errors while decoding UserData: \(Failure.failedDecodingFile.errorDescription)"); return .failure(.failedDecodingFile)} | |
let user = User(userID: userData.id, userName: userData.username.content, iconServer: userData.iconserver, iconFarm: userData.iconfarm) | |
_ = user.iconURL | |
return .success(user) | |
} | |
// Saving User Info with FileManager | |
func saveUserInfo(_ userData: Result<User, Failure>) { | |
let plistEncoder = PropertyListEncoder() | |
plistEncoder.outputFormat = .xml | |
let userDirectoryPath = FileManager.documentsDirectory | |
let fileToSaveInto = URL(fileURLWithPath: "SavedUserData", relativeTo: userDirectoryPath).appendingPathExtension("plist") | |
print("File location: \(fileToSaveInto.path)") | |
switch userData { | |
case .failure(let error ): | |
print("Error: \(error.localizedDescription)") | |
case .success(let user): | |
do { | |
let dataToBeSaved = try plistEncoder.encode(user) | |
try dataToBeSaved.write(to: fileToSaveInto, options: .atomic) | |
} catch { | |
print("Errors while writing user to Documents Directory: \(error.localizedDescription)") | |
} | |
} | |
} | |
// Retrieving User Info with FileManager | |
func retrieveUserInfo() throws -> User { | |
let plistDecoder = PropertyListDecoder() | |
let filePath = FileManager.documentsDirectory | |
let file = filePath.appendingPathComponent("SavedUserData").appendingPathExtension("plist") | |
guard let retrievedData = try? Data(contentsOf: file) else { print("Errors: \(Failure.missingFile.errorDescription)"); throw Failure.missingFile } | |
guard let decodedUserData = try? plistDecoder.decode(User.self, from: retrievedData) else { print("Error: \(Failure.failedDecodingFile.errorDescription)"); throw Failure.failedDecodingFile} | |
return decodedUserData | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment