StorageInternalTask.swift 2.2 KB

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