Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add new bundle extension for loading local file
- Loading branch information
Showing
1 changed file
with
60 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
import Foundation | ||
import Combine | ||
|
||
public extension Bundle { | ||
|
||
/// Version number via - CFBundleShortVersionString | ||
var versionNumber: String { | ||
infoDictionary?["CFBundleShortVersionString"] as? String ?? "" | ||
} | ||
|
||
/// Build number via - CFBundleVersion | ||
var buildNumber: String { | ||
infoDictionary?["CFBundleVersion"] as? String ?? "" | ||
} | ||
|
||
internal enum DataDecodingError: Error { | ||
case urlNotFound(String) | ||
case contentsOfURL(String) | ||
} | ||
|
||
/// Load model type from bundle resource | ||
/// - Parameters: | ||
/// - type: Type to load | ||
/// - file: File name | ||
/// - dateDecodingStrategy: date decoding strategy | ||
/// - keyDecodingStrategy: key decoding strategy | ||
/// - Returns: Future | ||
func decode<T: Decodable>( | ||
_ type: T.Type, from file: String, | ||
dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate, | ||
keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys | ||
) -> Deferred<Future<T, Error>> { | ||
Deferred { | ||
Future { promise in | ||
guard let url = self.url(forResource: file, withExtension: nil) else { | ||
promise(.failure(DataDecodingError.urlNotFound("Failed to locate \(file) in bundle."))) | ||
return | ||
} | ||
|
||
guard let data = try? Data(contentsOf: url) else { | ||
promise(.failure(DataDecodingError.contentsOfURL("Failed to load \(file) in bundle."))) | ||
return | ||
} | ||
|
||
let decoder = JSONDecoder() | ||
decoder.dateDecodingStrategy = dateDecodingStrategy | ||
decoder.keyDecodingStrategy = keyDecodingStrategy | ||
|
||
do { | ||
let type = try decoder.decode(T.self, from: data) | ||
promise(.success(type)) | ||
} catch { | ||
promise(.failure(error)) | ||
} | ||
|
||
} | ||
} | ||
} | ||
|
||
} |