Guest User

Untitled

a guest
Sep 19th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. class FileDownloader {
  2. func downloadFile(_ fileType: FileType, from urlString: String, as fileName: String, completion: @escaping (String?) -> Void) -> DownloadTask? {
  3. let filePath = LocalStorage.documentPath(of: fileType).appendingPathComponent(fileName)
  4. if !LocalStorage.fileExists(of: fileType, fileName: fileName) {
  5. #if DEBUG
  6. print("file not found at \(filePath)")
  7. #endif
  8.  
  9. let storage = Storage.storage()
  10. let storageRef = storage.reference(forURL: urlString)
  11. let downloadTask = storageRef.write(toFile: filePath) { (localUrl, error) in
  12. if let err = error {
  13. print("Error writing file: \(err)")
  14. } else {
  15. print("file saved at \(filePath.path)")
  16. completion(filePath.relativePath)
  17. }
  18. }
  19. return DownloadTask(firebaseDownloadTask: downloadTask)
  20. } else {
  21. memoireLogger.debug("file found at \(filePath)")
  22. completion(filePath.relativePath)
  23. return DownloadTask(firebaseDownloadTask: nil)
  24. }
  25. }
  26.  
  27. class DownloadTask {
  28. typealias Status = StorageTaskStatus
  29.  
  30. var firebaseDownloadTask: StorageDownloadTask?
  31. private var _id: String
  32. var id: String {
  33. get {
  34. return _id
  35. }
  36. }
  37.  
  38. init(firebaseDownloadTask: StorageDownloadTask?) {
  39. self.firebaseDownloadTask = firebaseDownloadTask
  40. self._id = UUID().uuidString
  41. }
  42.  
  43. func observe(_ status: Status, handler: @escaping (Snapshot) -> Void) {
  44. if firebaseDownloadTask == nil {
  45. let snapshot = Snapshot()
  46. handler(snapshot)
  47. } else {
  48. firebaseDownloadTask?.observe(status) { snapshot in
  49. handler(Snapshot(snapshot.progress))
  50. }
  51. }
  52. }
  53.  
  54. struct Snapshot {
  55. var progress: Progress?
  56.  
  57. init(_ progress: Progress? = nil) {
  58. if progress == nil {
  59. self.progress = Progress(totalUnitCount: 1)
  60. self.progress?.completedUnitCount = 1
  61. } else {
  62. self.progress = progress
  63. }
  64. }
  65. }
  66. }
  67. }
Add Comment
Please, Sign In to add comment