Last active
October 27, 2018 08:39
-
-
Save laevandus/b432179960156e29645d2c4e13764df8 to your computer and use it in GitHub Desktop.
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
typealias Identifier = String | |
enum Result { | |
case failed(Error) | |
case noData | |
case success(Identifier) | |
} | |
func storeData(_ dataProvider: @escaping () -> (Data?), identifier: Identifier = UUID().uuidString, completionHandler block: @escaping (Result) -> ()) { | |
queue.async(flags: .barrier) { | |
let url = self.url(forIdentifier: identifier) | |
guard let data = dataProvider(), !data.isEmpty else { | |
DispatchQueue.main.async { | |
block(.noData) | |
} | |
return | |
} | |
do { | |
try data.write(to: url, options: .atomic) | |
DispatchQueue.main.async { | |
block(.success(identifier)) | |
} | |
} | |
catch { | |
DispatchQueue.main.async { | |
block(.failed(error)) | |
} | |
} | |
} | |
} | |
// Example (adding data to data store with unique identifier): | |
persistentStore.storeData({ () -> (Data?) in | |
return image.jpegData(compressionQuality: 1.0) | |
}) { (result) in | |
switch result { | |
case .success(let identifier): | |
print("Stored data successfully with identifier \(identifier).") | |
case .noData: | |
print("No data to store.") | |
case .failed(let error): | |
print("Failed storing data with error \(error)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment