BackgroundAlertManager.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //
  2. // BackgroundAlertManager.swift
  3. // LoopFollow
  4. //
  5. // Created by Jonas Björkert on 2024-06-22.
  6. // Copyright © 2024 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import UserNotifications
  10. class BackgroundAlertManager {
  11. static let shared = BackgroundAlertManager()
  12. private init() {}
  13. private var isAlertScheduled: Bool = false
  14. func startBackgroundAlert() {
  15. isAlertScheduled = true
  16. scheduleBackgroundAlert()
  17. }
  18. func stopBackgroundAlert() {
  19. isAlertScheduled = false
  20. cancelBackgroundAlert()
  21. }
  22. func scheduleBackgroundAlert() {
  23. guard isAlertScheduled, UserDefaultsRepository.backgroundRefresh.value else { return }
  24. let content = UNMutableNotificationContent()
  25. content.title = "LoopFollow Background Refresh"
  26. content.body = "The app is not active, open the app to resume."
  27. content.sound = .defaultCritical
  28. content.categoryIdentifier = "loopfollow.background.alert"
  29. let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 360, repeats: false)
  30. let request = UNNotificationRequest(identifier: "loopfollow.background.alert", content: content, trigger: trigger)
  31. UNUserNotificationCenter.current().add(request) { error in
  32. if let error = error {
  33. print("Error scheduling background alert: \(error)")
  34. }
  35. }
  36. }
  37. private func cancelBackgroundAlert() {
  38. UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["loopfollow.background.alert"])
  39. }
  40. }