ScreenAwakeManager.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //
  2. // ScreenAwakeManager.swift
  3. // Nextcloud
  4. //
  5. // Created by Milen Pivchev on 18.09.24.
  6. // Copyright © 2024 Marino Faggiana. All rights reserved.
  7. //
  8. // Modified from https://github.com/ochococo/Insomnia
  9. import UIKit
  10. class ScreenAwakeManager {
  11. static let shared: ScreenAwakeManager = {
  12. let instance = ScreenAwakeManager()
  13. return instance
  14. }()
  15. /**
  16. This mode will change the behavior:
  17. - `disabled`: Nothing will change (disabled functionality).
  18. - `always`: Your iOS device will never timeout and lock.
  19. - `whenCharging`: Device will stay active as long as it's connected to charger.
  20. */
  21. var mode: AwakeMode = .off {
  22. didSet {
  23. updateMode()
  24. }
  25. }
  26. private unowned let device = UIDevice.current
  27. private unowned let notificationCenter = NotificationCenter.default
  28. private unowned let application = UIApplication.shared
  29. private init() {}
  30. private func startMonitoring() {
  31. device.isBatteryMonitoringEnabled = true
  32. notificationCenter.addObserver(self,
  33. selector: #selector(batteryStateDidChange),
  34. name: UIDevice.batteryStateDidChangeNotification, object: nil)
  35. }
  36. private func stopMonitoring() {
  37. notificationCenter.removeObserver(self)
  38. device.isBatteryMonitoringEnabled = false
  39. }
  40. @objc private func batteryStateDidChange(notification: NSNotification) {
  41. updateMode()
  42. }
  43. private func updateMode() {
  44. DispatchQueue.main.async { [self] in
  45. switch mode {
  46. case .whileCharging:
  47. startMonitoring()
  48. application.isIdleTimerDisabled = isPlugged
  49. case .on:
  50. stopMonitoring()
  51. application.isIdleTimerDisabled = true
  52. case .off:
  53. stopMonitoring()
  54. application.isIdleTimerDisabled = false
  55. }
  56. }
  57. }
  58. private var isPlugged: Bool {
  59. switch device.batteryState {
  60. case .unknown, .unplugged:
  61. return false
  62. default:
  63. return true
  64. }
  65. }
  66. deinit {
  67. stopMonitoring()
  68. application.isIdleTimerDisabled = false
  69. }
  70. }