HealthKitStateModel.swift 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import Combine
  2. import SwiftUI
  3. extension AppleHealthKit {
  4. final class StateModel: BaseStateModel<Provider> {
  5. @Injected() var healthKitManager: HealthKitManager!
  6. @Published var useAppleHealth = false
  7. @Published var needShowInformationTextForSetPermissions = false
  8. override func subscribe() {
  9. useAppleHealth = settingsManager.settings.useAppleHealth
  10. needShowInformationTextForSetPermissions = settingsManager.settings.needShowInformationTextForSetPermissions
  11. subscribeSetting(\.needShowInformationTextForSetPermissions, on: $needShowInformationTextForSetPermissions) { _ in }
  12. $useAppleHealth
  13. .removeDuplicates()
  14. .sink { [weak self] value in
  15. guard let self = self else { return }
  16. guard value else {
  17. self.settingsManager.settings.useAppleHealth = false
  18. self.needShowInformationTextForSetPermissions = false
  19. return
  20. }
  21. self.healthKitManager.requestPermission { status, error in
  22. guard error == nil else {
  23. return
  24. }
  25. self.settingsManager.settings.useAppleHealth = status
  26. self.healthKitManager.enableBackgroundDelivery()
  27. self.healthKitManager.createObserver()
  28. DispatchQueue.main.async {
  29. if !self.healthKitManager.areAllowAllPermissions {
  30. self.needShowInformationTextForSetPermissions = true
  31. }
  32. }
  33. }
  34. }
  35. .store(in: &lifetime)
  36. }
  37. }
  38. }