Created
September 19, 2018 19:19
-
-
Save EdmundLeex/b81cd608846cf08b5a0105c9194dc9ea 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
class FileDownloader { | |
func downloadFile(_ fileType: FileType, from urlString: String, as fileName: String, completion: @escaping (String?) -> Void) -> DownloadTask? { | |
let filePath = LocalStorage.documentPath(of: fileType).appendingPathComponent(fileName) | |
if !LocalStorage.fileExists(of: fileType, fileName: fileName) { | |
#if DEBUG | |
print("file not found at \(filePath)") | |
#endif | |
let storage = Storage.storage() | |
let storageRef = storage.reference(forURL: urlString) | |
let downloadTask = storageRef.write(toFile: filePath) { (localUrl, error) in | |
if let err = error { | |
print("Error writing file: \(err)") | |
} else { | |
print("file saved at \(filePath.path)") | |
completion(filePath.relativePath) | |
} | |
} | |
return DownloadTask(firebaseDownloadTask: downloadTask) | |
} else { | |
memoireLogger.debug("file found at \(filePath)") | |
completion(filePath.relativePath) | |
return DownloadTask(firebaseDownloadTask: nil) | |
} | |
} | |
class DownloadTask { | |
typealias Status = StorageTaskStatus | |
var firebaseDownloadTask: StorageDownloadTask? | |
private var _id: String | |
var id: String { | |
get { | |
return _id | |
} | |
} | |
init(firebaseDownloadTask: StorageDownloadTask?) { | |
self.firebaseDownloadTask = firebaseDownloadTask | |
self._id = UUID().uuidString | |
} | |
func observe(_ status: Status, handler: @escaping (Snapshot) -> Void) { | |
if firebaseDownloadTask == nil { | |
let snapshot = Snapshot() | |
handler(snapshot) | |
} else { | |
firebaseDownloadTask?.observe(status) { snapshot in | |
handler(Snapshot(snapshot.progress)) | |
} | |
} | |
} | |
struct Snapshot { | |
var progress: Progress? | |
init(_ progress: Progress? = nil) { | |
if progress == nil { | |
self.progress = Progress(totalUnitCount: 1) | |
self.progress?.completedUnitCount = 1 | |
} else { | |
self.progress = progress | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment