StorageInternalTask.swift 2.0 KB

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