NotificationAuthorization.swift 1.3 KB

12345678910111213141516171819202122232425262728293031
  1. // LoopFollow
  2. // NotificationAuthorization.swift
  3. import UserNotifications
  4. /// Requests notification authorization lazily, the first time the user opts into
  5. /// a feature that needs it (alarms). This keeps the system prompt off the very
  6. /// first launch so it doesn't front the onboarding flow.
  7. enum NotificationAuthorization {
  8. /// Asks for authorization only when the user hasn't decided yet. Safe to call
  9. /// repeatedly — it's a no-op once the status is determined. `completion` runs
  10. /// on the main queue after the prompt is dismissed (or immediately when the
  11. /// status was already determined), so a caller can wait for the system prompt
  12. /// before moving on.
  13. static func requestIfNeeded(completion: @escaping () -> Void = {}) {
  14. let center = UNUserNotificationCenter.current()
  15. center.getNotificationSettings { settings in
  16. guard settings.authorizationStatus == .notDetermined else {
  17. DispatchQueue.main.async { completion() }
  18. return
  19. }
  20. center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, _ in
  21. if !granted {
  22. LogManager.shared.log(category: .general, message: "User has declined notifications")
  23. }
  24. DispatchQueue.main.async { completion() }
  25. }
  26. }
  27. }
  28. }