Last active
May 4, 2017 15:43
-
-
Save nbasham/e1e3c3d70f8f16a563a0 to your computer and use it in GitHub Desktop.
Swift 3: Convenience methods to load and save an NSCoding object from the iOS directories.
This file contains 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
import Foundation | |
protocol IOSDirectoryFile { | |
static var dirSelector: FileManager.SearchPathDirectory { get } | |
} | |
extension IOSDirectoryFile { | |
static var url: URL { | |
return FileManager.default.urls(for: dirSelector, in: .userDomainMask)[0] | |
} | |
static func path(_ fileName: String) -> String { | |
return url.appendingPathComponent(fileName).path | |
} | |
static func load(_ fileName: String) -> Any? { | |
let fullPath = path(fileName) | |
return NSKeyedUnarchiver.unarchiveObject(withFile: fullPath) | |
} | |
static func save(_ object: Any, fileName: String) { | |
// may fail because it may not exist in sandbox, so check existence and create if necessary | |
if !FileManager.default.fileExists(atPath: url.absoluteString) { | |
try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) | |
} | |
let fullPath = path(fileName) | |
let b = NSKeyedArchiver.archiveRootObject(object, toFile: fullPath) | |
if !b { | |
print("Failed saving \(fullPath)") | |
} | |
} | |
static func remove(_ fileName: String) { | |
let fullPath = path(fileName) | |
try? FileManager.default.removeItem(atPath: fullPath) | |
} | |
} | |
/// Example usage: | |
/// - AppSupportFile.load("name.txt") | |
/// - AppSupportFile.save(fileContents, fileName: "name.txt") | |
/// - AppSupportFile.remove("name.txt") | |
class AppSupportFile: IOSDirectoryFile { | |
static var dirSelector: FileManager.SearchPathDirectory { return .applicationSupportDirectory } | |
} | |
/// Example usage: | |
/// - DocumentsFile.load("name.txt") | |
/// - DocumentsFile.save(fileContents, fileName: "name.txt") | |
/// - DocumentsFile.remove("name.txt") | |
class DocumentsFile: IOSDirectoryFile { | |
static var dirSelector: FileManager.SearchPathDirectory { return .documentDirectory } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage:
AppSupportFile.load("name.txt")
AppSupportFile.save(fileContents, fileName: "name.txt")
AppSupportFile.remove("name.txt")
or
DocumentsFile.load("name.txt")
DocumentsFile.save(fileContents, fileName: "name.txt")
DocumentsFile.remove("name.txt")