Skip to content

Instantly share code, notes, and snippets.

@nbasham
Last active May 4, 2017 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nbasham/e1e3c3d70f8f16a563a0 to your computer and use it in GitHub Desktop.
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.
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 }
}
@nbasham
Copy link
Author

nbasham commented Mar 21, 2016

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")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment