77 lines
1.9 KiB
Swift
77 lines
1.9 KiB
Swift
//
|
|
// BatteryService.swift
|
|
// TheNoiseClock
|
|
//
|
|
// Created by Matt Bruce on 9/7/25.
|
|
//
|
|
|
|
import Foundation
|
|
import Combine
|
|
import UIKit
|
|
|
|
/// Service for monitoring device battery level and state
|
|
@Observable
|
|
class BatteryService {
|
|
|
|
// MARK: - Properties
|
|
static let shared = BatteryService()
|
|
|
|
var batteryLevel: Int = 100
|
|
var isCharging: Bool = false
|
|
|
|
private var cancellables = Set<AnyCancellable>()
|
|
|
|
// MARK: - Initialization
|
|
private init() {
|
|
setupBatteryMonitoring()
|
|
}
|
|
|
|
// MARK: - Public Methods
|
|
func startMonitoring() {
|
|
#if canImport(UIKit)
|
|
UIDevice.current.isBatteryMonitoringEnabled = true
|
|
updateBatteryInfo()
|
|
#endif
|
|
}
|
|
|
|
func stopMonitoring() {
|
|
#if canImport(UIKit)
|
|
UIDevice.current.isBatteryMonitoringEnabled = false
|
|
#endif
|
|
}
|
|
|
|
// MARK: - Private Methods
|
|
private func setupBatteryMonitoring() {
|
|
#if canImport(UIKit)
|
|
// Listen for battery level changes
|
|
NotificationCenter.default.publisher(for: UIDevice.batteryLevelDidChangeNotification)
|
|
.sink { [weak self] _ in
|
|
self?.updateBatteryInfo()
|
|
}
|
|
.store(in: &cancellables)
|
|
|
|
// Listen for battery state changes
|
|
NotificationCenter.default.publisher(for: UIDevice.batteryStateDidChangeNotification)
|
|
.sink { [weak self] _ in
|
|
self?.updateBatteryInfo()
|
|
}
|
|
.store(in: &cancellables)
|
|
#endif
|
|
}
|
|
|
|
private func updateBatteryInfo() {
|
|
#if canImport(UIKit)
|
|
let device = UIDevice.current
|
|
|
|
// Update battery level
|
|
let level = device.batteryLevel
|
|
if level >= 0 {
|
|
batteryLevel = Int((level * 100).rounded())
|
|
}
|
|
|
|
// Update charging state
|
|
isCharging = device.batteryState == .charging
|
|
#endif
|
|
}
|
|
}
|