Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- }
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment