123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- //
- // ScreenAwakeManager.swift
- // Nextcloud
- //
- // Created by Milen Pivchev on 18.09.24.
- // Copyright © 2024 Marino Faggiana. All rights reserved.
- //
- // Modified from https://github.com/ochococo/Insomnia
- import UIKit
- /**
- Sometimes you want your iPhone to stay active a little bit longer is it an import or just game interface.
- This simple class aims to simplify the code and give you a well tested solution.
- */
- class ScreenAwakeManager {
- static let shared: ScreenAwakeManager = {
- let instance = ScreenAwakeManager()
- return instance
- }()
- /**
- This mode will change the behavior:
- - `disabled`: Nothing will change (disabled functionality).
- - `always`: Your iOS device will never timeout and lock.
- - `whenCharging`: Device will stay active as long as it's connected to charger.
- */
- var mode: AwakeMode = .off {
- didSet {
- updateMode()
- }
- }
- private unowned let device = UIDevice.current
- private unowned let notificationCenter = NotificationCenter.default
- private unowned let application = UIApplication.shared
- private init() {}
- private func startMonitoring() {
- device.isBatteryMonitoringEnabled = true
- notificationCenter.addObserver(self,
- selector: #selector(batteryStateDidChange),
- name: UIDevice.batteryStateDidChangeNotification, object: nil)
- }
- private func stopMonitoring() {
- notificationCenter.removeObserver(self)
- device.isBatteryMonitoringEnabled = false
- }
- @objc private func batteryStateDidChange(notification: NSNotification) {
- updateMode()
- }
- private func updateMode() {
- DispatchQueue.main.async { [self] in
- switch mode {
- case .whileCharging:
- startMonitoring()
- application.isIdleTimerDisabled = isPlugged
- case .on:
- stopMonitoring()
- application.isIdleTimerDisabled = true
- case .off:
- stopMonitoring()
- application.isIdleTimerDisabled = false
- }
- }
- }
- private var isPlugged: Bool {
- switch device.batteryState {
- case .unknown, .unplugged:
- return false
- default:
- return true
- }
- }
- deinit {
- stopMonitoring()
- application.isIdleTimerDisabled = false
- }
- }
|