AlertPermissionsChecker.swift 2.0 KB

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