Skip to content

Instantly share code, notes, and snippets.

@mitulmanish
Created April 8, 2018 03:11
Show Gist options
  • Save mitulmanish/ca972301fd51e8f238e5875c7a51d51e to your computer and use it in GitHub Desktop.
Save mitulmanish/ca972301fd51e8f238e5875c7a51d51e to your computer and use it in GitHub Desktop.
struct AssetSaveHelper {
static var documentsDirectoryUrl: URL? {
return FileManager().urls(for: .cachesDirectory, in: .userDomainMask).first
}
static var cacheURL: URL? {
guard let url = documentsDirectoryUrl else {
return nil
}
let cacheURL = url.appendingPathComponent("images", isDirectory: true)
return cacheURL
}
static func cacheDataForTag(_ data: Data, tag: String) throws {
guard let cacheURL = cacheURL else {
return
}
let path = cacheURL.path
if !FileManager().fileExists(atPath: path) {
do {
try FileManager().createDirectory(at: cacheURL, withIntermediateDirectories: false, attributes: nil)
} catch let err {
throw err
}
}
let dataURL = cacheURL.appendingPathComponent(tag)
do {
try data.write(to: dataURL, options: [.atomic])
} catch let err {
throw err
}
}
static func cachedDataForTag(_ tag: String?) throws -> Data? {
guard let tag = tag, let dataURL = cacheURL?.appendingPathComponent(tag) else {
return nil
}
do {
let data = try Data(contentsOf: dataURL)
return data
} catch let err {
throw err
}
}
static func clearDirectory() {
guard let documentsUrl = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).last else {
return
}
do {
if let directoryName = try FileManager.default.contentsOfDirectory(atPath: documentsUrl.path).first(where: { $0 == "images" }) {
let file = documentsUrl.appendingPathComponent(directoryName)
do {
try FileManager.default.removeItem(at: file)
} catch let err {
print(err.localizedDescription)
}
}
} catch let err {
print(err.localizedDescription)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment