AlertPermissionsChecker.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import Combine
  2. import Foundation
  3. import LoopKit
  4. import SwiftUI
  5. import Swinject
  6. protocol AlertPermissionsCheckerDelegate: AnyObject {
  7. func notificationsPermissions(requiresRiskMitigation: Bool, scheduledDeliveryEnabled: Bool)
  8. }
  9. public class AlertPermissionsChecker: ObservableObject, Injectable {
  10. @Environment(\.appName) private var appName
  11. private lazy var cancellables = Set<AnyCancellable>()
  12. private var listeningToNotificationCenter = false
  13. @Injected() private var apsManager: APSManager!
  14. @Injected() private var router: Router!
  15. @Published var notificationsDisabled: Bool = false
  16. init(resolver: Resolver) {
  17. injectServices(resolver)
  18. Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)
  19. .sink { [weak self] _ in
  20. self?.check()
  21. }
  22. .store(in: &cancellables)
  23. Foundation.NotificationCenter.default.publisher(for: UIApplication.didEnterBackgroundNotification)
  24. .sink { [weak self] _ in
  25. self?.check()
  26. }
  27. .store(in: &cancellables)
  28. }
  29. func checkNow() {
  30. check {
  31. // Note: we do this, instead of calling notificationCenterSettingsChanged directly, so that we only
  32. // get called when it _changes_.
  33. self.listenToNotificationCenter()
  34. }
  35. }
  36. private func check(then completion: (() -> Void)? = nil) {
  37. UNUserNotificationCenter.current().getNotificationSettings { settings in
  38. DispatchQueue.main.async {
  39. self.notificationsDisabled = settings.alertSetting == .disabled
  40. completion?()
  41. }
  42. }
  43. }
  44. }
  45. extension AlertPermissionsChecker {
  46. private func listenToNotificationCenter() {
  47. if !listeningToNotificationCenter {
  48. $notificationsDisabled
  49. .receive(on: RunLoop.main)
  50. .removeDuplicates()
  51. .sink(receiveValue: notificationCenterSettingsChanged)
  52. .store(in: &cancellables)
  53. listeningToNotificationCenter = true
  54. }
  55. }
  56. private func notificationCenterSettingsChanged(_: Bool) {
  57. // TODO: Add processing for other actions in delegate AlertManager, InAppAlertScheduler, etc., from Loop
  58. debug(.default, "notificationCenterSettingsChanged")
  59. }
  60. }