BackgroundAssertion.swift 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //
  2. // BackgroundAssertion.swift
  3. // Alamofire
  4. //
  5. // Created by Jon Shier on 6/19/22.
  6. // Copyright © 2022 Alamofire. All rights reserved.
  7. //
  8. import Foundation
  9. #if os(iOS) || os(tvOS) || os(watchOS)
  10. final class BackgroundAssertion {
  11. private static let shared = BackgroundAssertion()
  12. static func start() {
  13. _ = shared
  14. }
  15. @Protected private var isActive = false
  16. private let group: DispatchGroup
  17. private init() {
  18. NSLog("*** BackgroundAssertion.init")
  19. group = DispatchGroup()
  20. ProcessInfo().performExpiringActivity(withReason: "org.alamofire.session.backgroundAssertion") { [self] isExpired in
  21. if isExpired {
  22. guard isActive else { return }
  23. group.leave()
  24. } else {
  25. isActive = true
  26. group.enter()
  27. group.notify(queue: .global()) {
  28. NSLog("*** BackgroundAssertion completed.")
  29. }
  30. // Block until canceled or expired.
  31. group.wait()
  32. isActive = false
  33. }
  34. }
  35. }
  36. deinit {
  37. guard isActive else { return }
  38. group.leave()
  39. }
  40. }
  41. #endif