ScreenAwakeManager.swift 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. /**
  11. Sometimes you want your iPhone to stay active a little bit longer is it an import or just game interface.
  12. This simple class aims to simplify the code and give you a well tested solution.
  13. */
  14. class ScreenAwakeManager {
  15. static let shared: ScreenAwakeManager = {
  16. let instance = ScreenAwakeManager()
  17. return instance
  18. }()
  19. /**
  20. This mode will change the behavior:
  21. - `disabled`: Nothing will change (disabled functionality).
  22. - `always`: Your iOS device will never timeout and lock.
  23. - `whenCharging`: Device will stay active as long as it's connected to charger.
  24. */
  25. var mode: AwakeMode = .off {
  26. didSet {
  27. updateMode()
  28. }
  29. }
  30. private unowned let device = UIDevice.current
  31. private unowned let notificationCenter = NotificationCenter.default
  32. private unowned let application = UIApplication.shared
  33. private init() {}
  34. private func startMonitoring() {
  35. device.isBatteryMonitoringEnabled = true
  36. notificationCenter.addObserver(self,
  37. selector: #selector(batteryStateDidChange),
  38. name: UIDevice.batteryStateDidChangeNotification, object: nil)
  39. }
  40. private func stopMonitoring() {
  41. notificationCenter.removeObserver(self)
  42. device.isBatteryMonitoringEnabled = false
  43. }
  44. @objc private func batteryStateDidChange(notification: NSNotification) {
  45. updateMode()
  46. }
  47. private func updateMode() {
  48. DispatchQueue.main.async { [self] in
  49. switch mode {
  50. case .whileCharging:
  51. startMonitoring()
  52. application.isIdleTimerDisabled = isPlugged
  53. case .on:
  54. stopMonitoring()
  55. application.isIdleTimerDisabled = true
  56. case .off:
  57. stopMonitoring()
  58. application.isIdleTimerDisabled = false
  59. }
  60. }
  61. }
  62. private var isPlugged: Bool {
  63. switch device.batteryState {
  64. case .unknown, .unplugged:
  65. return false
  66. default:
  67. return true
  68. }
  69. }
  70. deinit {
  71. stopMonitoring()
  72. application.isIdleTimerDisabled = false
  73. }
  74. }