StorageDeleteTask.swift 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2022 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. #if COCOAPODS
  16. import GTMSessionFetcher
  17. #else
  18. import GTMSessionFetcherCore
  19. #endif
  20. /**
  21. * Task which provides the ability to delete an object in Firebase Storage.
  22. */
  23. class StorageDeleteTask: StorageTask, StorageTaskManagement {
  24. private var fetcher: GTMSessionFetcher?
  25. private var fetcherCompletion: ((Data?, NSError?) -> Void)?
  26. private var taskCompletion: ((_ error: Error?) -> Void)?
  27. init(reference: StorageReference,
  28. fetcherService: GTMSessionFetcherService,
  29. queue: DispatchQueue,
  30. completion: ((_: Error?) -> Void)?) {
  31. super.init(reference: reference, service: fetcherService, queue: queue)
  32. taskCompletion = completion
  33. }
  34. deinit {
  35. self.fetcher?.stopFetching()
  36. }
  37. /**
  38. * Prepares a task and begins execution.
  39. */
  40. func enqueue() {
  41. let completion = taskCompletion
  42. taskCompletion = { (error: Error?) in
  43. completion?(error)
  44. // Reference self in completion handler in order to retain self until completion is called.
  45. self.taskCompletion = nil
  46. }
  47. dispatchQueue.async { [weak self] in
  48. guard let self = self else { return }
  49. self.state = .queueing
  50. var request = self.baseRequest
  51. request.httpMethod = "DELETE"
  52. request.timeoutInterval = self.reference.storage.maxOperationRetryTime
  53. let fetcher = self.fetcherService.fetcher(with: request)
  54. fetcher.comment = "DeleteTask"
  55. self.fetcher = fetcher
  56. self.fetcherCompletion = { [weak self] (data: Data?, error: NSError?) in
  57. guard let self = self else { return }
  58. if let error, self.error == nil {
  59. self.error = StorageErrorCode.error(withServerError: error, ref: self.reference)
  60. }
  61. self.taskCompletion?(self.error)
  62. self.fetcherCompletion = nil
  63. }
  64. self.fetcher?.beginFetch { [weak self] data, error in
  65. self?.fetcherCompletion?(data, error as? NSError)
  66. }
  67. }
  68. }
  69. }