StorageInternalTask.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2024 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. /// Implement StorageTasks that are not directly exposed via the public API.
  21. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  22. class StorageInternalTask: StorageTask {
  23. private var fetcher: GTMSessionFetcher?
  24. @discardableResult
  25. init(reference: StorageReference,
  26. queue: DispatchQueue,
  27. request: URLRequest? = nil,
  28. httpMethod: String,
  29. fetcherComment: String,
  30. completion: ((_: Data?, _: Error?) -> Void)?) {
  31. super.init(reference: reference, queue: queue)
  32. // Prepare a task and begins execution.
  33. dispatchQueue.async { [self] in
  34. self.state = .queueing
  35. Task {
  36. let fetcherService = await StorageFetcherService.shared.service(reference.storage)
  37. var request = request ?? self.baseRequest
  38. request.httpMethod = httpMethod
  39. request.timeoutInterval = self.reference.storage.maxOperationRetryTime
  40. let fetcher = fetcherService.fetcher(with: request)
  41. fetcher.comment = fetcherComment
  42. self.fetcher = fetcher
  43. let callbackQueue = reference.storage.callbackQueue
  44. do {
  45. let data = try await self.fetcher?.beginFetch()
  46. callbackQueue.async {
  47. completion?(data, nil)
  48. }
  49. } catch {
  50. callbackQueue.async {
  51. completion?(nil, StorageErrorCode.error(withServerError: error as NSError,
  52. ref: self.reference))
  53. }
  54. }
  55. }
  56. }
  57. }
  58. deinit {
  59. self.fetcher?.stopFetching()
  60. }
  61. }