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
func loadData<T>(forIdentifier identifier: Identifier, dataTransformer: @escaping (Data) -> (T?), completionHandler block: @escaping (T?) -> ()) { | |
queue.async { | |
let url = self.url(forIdentifier: identifier) | |
guard FileManager.default.fileExists(atPath: url.path) else { | |
DispatchQueue.main.async { | |
block(nil) | |
} | |
return | |
} | |
do { | |
let data = try Data(contentsOf: url, options: .mappedIfSafe) | |
let object = dataTransformer(data) | |
DispatchQueue.main.async { | |
block(object) | |
} | |
} | |
catch { | |
print("Failed reading data at URL \(url).") | |
DispatchQueue.main.async { | |
block(nil) | |
} | |
} | |
} | |
} | |
// Example | |
persistentStore.loadData(forIdentifier: "my_identifier", dataTransformer: { UIImage(data: $0) }) { (image) in | |
guard let image = image else { | |
print("Failed loading image.") | |
return | |
} | |
print(image) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment