Skip to content

Instantly share code, notes, and snippets.

@nbasham

nbasham/IOSDirectoryFile

Last active May 4, 2017
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@nbasham 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