feat(ios): Enhance battery optimization and notification management
Description: - Add battery status and power state monitoring - Implement adaptive scheduling based on battery levels - Add maintenance worker for background tasks - Enhance logging with structured DailyNotificationLogger - Add configuration management with DailyNotificationConfig - Define constants in DailyNotificationConstants - Improve error handling and recovery mechanisms Testing: - Add comprehensive test coverage for battery optimization - Add test coverage for power state management - Add test coverage for maintenance tasks - Add test coverage for configuration management - Add test coverage for constants validation Documentation: - Add comprehensive file-level documentation - Add method-level documentation - Add test documentation - Add configuration documentation This commit improves the iOS implementation's reliability and battery efficiency by adding robust error handling, logging, and configuration management to make the plugin more maintainable and debuggable.
This commit is contained in:
@@ -27,5 +27,59 @@ public struct DailyNotificationConfig {
|
||||
/// Number of days to retain delivered notifications
|
||||
public var retentionDays = 7
|
||||
|
||||
/// Whether adaptive scheduling is enabled
|
||||
public var adaptiveSchedulingEnabled = true
|
||||
|
||||
/// Battery level thresholds for adaptive scheduling
|
||||
public struct BatteryThresholds {
|
||||
public static let critical = 15
|
||||
public static let low = 30
|
||||
public static let medium = 50
|
||||
}
|
||||
|
||||
/// Time intervals for different battery levels (in seconds)
|
||||
public struct SchedulingIntervals {
|
||||
public static let critical = TimeInterval(4 * 60 * 60) // 4 hours
|
||||
public static let low = TimeInterval(2 * 60 * 60) // 2 hours
|
||||
public static let medium = TimeInterval(60 * 60) // 1 hour
|
||||
public static let normal = TimeInterval(30 * 60) // 30 minutes
|
||||
}
|
||||
|
||||
/// Wake lock duration based on battery level (in seconds)
|
||||
public struct WakeLockDurations {
|
||||
public static let critical = TimeInterval(30) // 30 seconds
|
||||
public static let low = TimeInterval(45) // 45 seconds
|
||||
public static let normal = TimeInterval(60) // 1 minute
|
||||
}
|
||||
|
||||
private init() {}
|
||||
|
||||
/// Resets all configuration options to their default values
|
||||
public mutating func resetToDefaults() {
|
||||
maxNotificationsPerDay = 10
|
||||
defaultTimeZone = TimeZone.current
|
||||
loggingEnabled = true
|
||||
retentionDays = 7
|
||||
adaptiveSchedulingEnabled = true
|
||||
}
|
||||
|
||||
/// Validates and sets the maximum notifications per day
|
||||
/// - Parameter value: The new maximum notifications value
|
||||
/// - Throws: DailyNotificationError if the value is invalid
|
||||
public mutating func setMaxNotificationsPerDay(_ value: Int) throws {
|
||||
guard value > 0 else {
|
||||
throw DailyNotificationError.invalidParameters("Max notifications per day must be greater than 0")
|
||||
}
|
||||
maxNotificationsPerDay = value
|
||||
}
|
||||
|
||||
/// Validates and sets the retention days
|
||||
/// - Parameter value: The new retention days value
|
||||
/// - Throws: DailyNotificationError if the value is invalid
|
||||
public mutating func setRetentionDays(_ value: Int) throws {
|
||||
guard value > 0 else {
|
||||
throw DailyNotificationError.invalidParameters("Retention days must be greater than 0")
|
||||
}
|
||||
retentionDays = value
|
||||
}
|
||||
}
|
||||
122
ios/Plugin/DailyNotificationMaintenanceWorker.swift
Normal file
122
ios/Plugin/DailyNotificationMaintenanceWorker.swift
Normal file
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* DailyNotificationMaintenanceWorker.swift
|
||||
* Daily Notification Plugin for Capacitor
|
||||
*
|
||||
* Handles background maintenance tasks for notifications
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
import UserNotifications
|
||||
|
||||
/// Handles background maintenance tasks for the notification plugin
|
||||
public class DailyNotificationMaintenanceWorker {
|
||||
/// Shared instance for singleton access
|
||||
public static let shared = DailyNotificationMaintenanceWorker()
|
||||
|
||||
private let notificationCenter = UNUserNotificationCenter.current()
|
||||
private let powerManager = DailyNotificationPowerManager.shared
|
||||
|
||||
private init() {}
|
||||
|
||||
/// Performs maintenance tasks
|
||||
public func performMaintenance() {
|
||||
DailyNotificationLogger.shared.log(.info, "Starting maintenance tasks")
|
||||
|
||||
// Update battery status
|
||||
_ = powerManager.getBatteryStatus()
|
||||
|
||||
// Clean up old notifications
|
||||
cleanupOldNotifications()
|
||||
|
||||
// Reschedule missed notifications
|
||||
rescheduleMissedNotifications()
|
||||
|
||||
DailyNotificationLogger.shared.log(.info, "Maintenance tasks completed")
|
||||
}
|
||||
|
||||
private func cleanupOldNotifications() {
|
||||
let cutoffDate = Date().addingTimeInterval(-Double(DailyNotificationConfig.shared.retentionDays * 24 * 60 * 60))
|
||||
|
||||
notificationCenter.getDeliveredNotifications { notifications in
|
||||
let oldNotifications = notifications.filter { $0.date < cutoffDate }
|
||||
|
||||
if !oldNotifications.isEmpty {
|
||||
let identifiers = oldNotifications.map { $0.request.identifier }
|
||||
self.notificationCenter.removeDeliveredNotifications(withIdentifiers: identifiers)
|
||||
|
||||
DailyNotificationLogger.shared.log(
|
||||
.info,
|
||||
"Cleaned up \(identifiers.count) old notifications"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func rescheduleMissedNotifications() {
|
||||
notificationCenter.getPendingNotificationRequests { requests in
|
||||
let now = Date()
|
||||
|
||||
for request in requests {
|
||||
guard let trigger = request.trigger as? UNCalendarNotificationTrigger,
|
||||
let nextTriggerDate = trigger.nextTriggerDate() else {
|
||||
continue
|
||||
}
|
||||
|
||||
// If the next trigger date is more than 24 hours in the past
|
||||
if nextTriggerDate.timeIntervalSince(now) < -24 * 60 * 60 {
|
||||
// Reschedule the notification
|
||||
let content = request.content.mutableCopy() as! UNMutableNotificationContent
|
||||
let newRequest = UNNotificationRequest(
|
||||
identifier: request.identifier,
|
||||
content: content,
|
||||
trigger: trigger
|
||||
)
|
||||
|
||||
self.notificationCenter.add(newRequest) { error in
|
||||
if let error = error {
|
||||
DailyNotificationLogger.shared.log(
|
||||
.error,
|
||||
"Failed to reschedule notification: \(error.localizedDescription)"
|
||||
)
|
||||
} else {
|
||||
DailyNotificationLogger.shared.log(
|
||||
.info,
|
||||
"Successfully rescheduled notification: \(request.identifier)"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Schedules the next maintenance window
|
||||
public func scheduleNextMaintenance() {
|
||||
let trigger = UNTimeIntervalNotificationTrigger(
|
||||
timeInterval: DailyNotificationConfig.SchedulingIntervals.normal,
|
||||
repeats: true
|
||||
)
|
||||
|
||||
let content = UNMutableNotificationContent()
|
||||
content.title = "Maintenance"
|
||||
content.body = "Performing notification maintenance"
|
||||
content.sound = nil
|
||||
|
||||
let request = UNNotificationRequest(
|
||||
identifier: "maintenance-window",
|
||||
content: content,
|
||||
trigger: trigger
|
||||
)
|
||||
|
||||
notificationCenter.add(request) { error in
|
||||
if let error = error {
|
||||
DailyNotificationLogger.shared.log(
|
||||
.error,
|
||||
"Failed to schedule maintenance window: \(error.localizedDescription)"
|
||||
)
|
||||
} else {
|
||||
DailyNotificationLogger.shared.log(.info, "Maintenance window scheduled")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@ import UserNotifications
|
||||
@objc(DailyNotificationPlugin)
|
||||
public class DailyNotificationPlugin: CAPPlugin {
|
||||
private let notificationCenter = UNUserNotificationCenter.current()
|
||||
private let powerManager = DailyNotificationPowerManager.shared
|
||||
private let maintenanceWorker = DailyNotificationMaintenanceWorker.shared
|
||||
|
||||
private var settings: [String: Any] = [
|
||||
"sound": true,
|
||||
@@ -39,6 +41,15 @@ public class DailyNotificationPlugin: CAPPlugin {
|
||||
return
|
||||
}
|
||||
|
||||
// Check battery optimization status
|
||||
let batteryStatus = powerManager.getBatteryStatus()
|
||||
if batteryStatus["level"] as? Int ?? 100 < DailyNotificationConfig.BatteryThresholds.critical {
|
||||
DailyNotificationLogger.shared.log(
|
||||
.warning,
|
||||
"Warning: Battery level is critical"
|
||||
)
|
||||
}
|
||||
|
||||
// Parse time string (HH:mm format)
|
||||
let timeComponents = time.split(separator: ":")
|
||||
guard timeComponents.count == 2,
|
||||
@@ -52,8 +63,8 @@ public class DailyNotificationPlugin: CAPPlugin {
|
||||
|
||||
// Create notification content
|
||||
let content = UNMutableNotificationContent()
|
||||
content.title = call.getString("title") ?? "Daily Notification"
|
||||
content.body = call.getString("body") ?? "Your daily update is ready"
|
||||
content.title = call.getString("title") ?? DailyNotificationConstants.defaultTitle
|
||||
content.body = call.getString("body") ?? DailyNotificationConstants.defaultBody
|
||||
content.sound = call.getBool("sound", true) ? .default : nil
|
||||
|
||||
// Set priority
|
||||
@@ -110,8 +121,16 @@ public class DailyNotificationPlugin: CAPPlugin {
|
||||
// Schedule notification
|
||||
notificationCenter.add(request) { error in
|
||||
if let error = error {
|
||||
DailyNotificationLogger.shared.log(
|
||||
.error,
|
||||
"Failed to schedule notification: \(error.localizedDescription)"
|
||||
)
|
||||
call.reject("Failed to schedule notification: \(error.localizedDescription)")
|
||||
} else {
|
||||
DailyNotificationLogger.shared.log(
|
||||
.info,
|
||||
"Successfully scheduled notification for \(time)"
|
||||
)
|
||||
call.resolve()
|
||||
}
|
||||
}
|
||||
@@ -255,8 +274,25 @@ public class DailyNotificationPlugin: CAPPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
@objc func getBatteryStatus(_ call: CAPPluginCall) {
|
||||
let status = powerManager.getBatteryStatus()
|
||||
call.resolve(status)
|
||||
}
|
||||
|
||||
@objc func getPowerState(_ call: CAPPluginCall) {
|
||||
let state = powerManager.getPowerState()
|
||||
call.resolve(state)
|
||||
}
|
||||
|
||||
@objc func setAdaptiveScheduling(_ call: CAPPluginCall) {
|
||||
let enabled = call.getBool("enabled", true)
|
||||
powerManager.setAdaptiveScheduling(enabled)
|
||||
call.resolve()
|
||||
}
|
||||
|
||||
public override func load() {
|
||||
notificationCenter.delegate = self
|
||||
maintenanceWorker.scheduleNextMaintenance()
|
||||
}
|
||||
|
||||
private func isValidTime(_ time: String) -> Bool {
|
||||
|
||||
153
ios/Plugin/DailyNotificationPowerManager.swift
Normal file
153
ios/Plugin/DailyNotificationPowerManager.swift
Normal file
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* DailyNotificationPowerManager.swift
|
||||
* Daily Notification Plugin for Capacitor
|
||||
*
|
||||
* Manages power state and battery optimization for notifications
|
||||
*/
|
||||
|
||||
import Foundation
|
||||
import UIKit
|
||||
import UserNotifications
|
||||
|
||||
/// Manages power state and battery optimization for the notification plugin
|
||||
public class DailyNotificationPowerManager {
|
||||
/// Shared instance for singleton access
|
||||
public static let shared = DailyNotificationPowerManager()
|
||||
|
||||
private var batteryLevel: Float = 1.0
|
||||
private var isCharging = false
|
||||
private var lastBatteryCheck: Date = Date()
|
||||
private var powerState: UIDevice.BatteryState = .unknown
|
||||
private var adaptiveSchedulingEnabled = true
|
||||
|
||||
private init() {
|
||||
setupBatteryMonitoring()
|
||||
}
|
||||
|
||||
private func setupBatteryMonitoring() {
|
||||
UIDevice.current.isBatteryMonitoringEnabled = true
|
||||
updateBatteryStatus()
|
||||
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(batteryLevelDidChange),
|
||||
name: UIDevice.batteryLevelDidChangeNotification,
|
||||
object: nil
|
||||
)
|
||||
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(batteryStateDidChange),
|
||||
name: UIDevice.batteryStateDidChangeNotification,
|
||||
object: nil
|
||||
)
|
||||
}
|
||||
|
||||
@objc private func batteryLevelDidChange() {
|
||||
updateBatteryStatus()
|
||||
}
|
||||
|
||||
@objc private func batteryStateDidChange() {
|
||||
updateBatteryStatus()
|
||||
}
|
||||
|
||||
private func updateBatteryStatus() {
|
||||
batteryLevel = UIDevice.current.batteryLevel
|
||||
isCharging = UIDevice.current.batteryState == .charging
|
||||
powerState = UIDevice.current.batteryState
|
||||
lastBatteryCheck = Date()
|
||||
|
||||
DailyNotificationLogger.shared.log(
|
||||
.debug,
|
||||
"Battery status updated: \(Int(batteryLevel * 100))% (\(isCharging ? "charging" : "not charging"))"
|
||||
)
|
||||
}
|
||||
|
||||
/// Gets the current battery status
|
||||
/// - Returns: Dictionary containing battery information
|
||||
public func getBatteryStatus() -> [String: Any] {
|
||||
return [
|
||||
"level": Int(batteryLevel * 100),
|
||||
"isCharging": isCharging,
|
||||
"lastCheck": lastBatteryCheck.timeIntervalSince1970,
|
||||
"powerState": getPowerStateString()
|
||||
]
|
||||
}
|
||||
|
||||
/// Gets the current power state
|
||||
/// - Returns: Dictionary containing power state information
|
||||
public func getPowerState() -> [String: Any] {
|
||||
return [
|
||||
"powerState": getPowerStateString(),
|
||||
"adaptiveScheduling": adaptiveSchedulingEnabled,
|
||||
"batteryLevel": Int(batteryLevel * 100),
|
||||
"isCharging": isCharging,
|
||||
"lastCheck": lastBatteryCheck.timeIntervalSince1970
|
||||
]
|
||||
}
|
||||
|
||||
/// Sets whether adaptive scheduling is enabled
|
||||
/// - Parameter enabled: Whether to enable adaptive scheduling
|
||||
public func setAdaptiveScheduling(_ enabled: Bool) {
|
||||
adaptiveSchedulingEnabled = enabled
|
||||
DailyNotificationLogger.shared.log(
|
||||
.info,
|
||||
"Adaptive scheduling \(enabled ? "enabled" : "disabled")"
|
||||
)
|
||||
}
|
||||
|
||||
/// Gets the appropriate scheduling interval based on battery level
|
||||
/// - Returns: TimeInterval for scheduling
|
||||
public func getSchedulingInterval() -> TimeInterval {
|
||||
guard adaptiveSchedulingEnabled else {
|
||||
return DailyNotificationConfig.SchedulingIntervals.normal
|
||||
}
|
||||
|
||||
let batteryPercentage = Int(batteryLevel * 100)
|
||||
|
||||
switch batteryPercentage {
|
||||
case ..<DailyNotificationConfig.BatteryThresholds.critical:
|
||||
return DailyNotificationConfig.SchedulingIntervals.critical
|
||||
case ..<DailyNotificationConfig.BatteryThresholds.low:
|
||||
return DailyNotificationConfig.SchedulingIntervals.low
|
||||
case ..<DailyNotificationConfig.BatteryThresholds.medium:
|
||||
return DailyNotificationConfig.SchedulingIntervals.medium
|
||||
default:
|
||||
return DailyNotificationConfig.SchedulingIntervals.normal
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the appropriate wake lock duration based on battery level
|
||||
/// - Returns: TimeInterval for wake lock
|
||||
public func getWakeLockDuration() -> TimeInterval {
|
||||
let batteryPercentage = Int(batteryLevel * 100)
|
||||
|
||||
switch batteryPercentage {
|
||||
case ..<DailyNotificationConfig.BatteryThresholds.critical:
|
||||
return DailyNotificationConfig.WakeLockDurations.critical
|
||||
case ..<DailyNotificationConfig.BatteryThresholds.low:
|
||||
return DailyNotificationConfig.WakeLockDurations.low
|
||||
default:
|
||||
return DailyNotificationConfig.WakeLockDurations.normal
|
||||
}
|
||||
}
|
||||
|
||||
private func getPowerStateString() -> String {
|
||||
switch powerState {
|
||||
case .charging:
|
||||
return "CHARGING"
|
||||
case .full:
|
||||
return "FULL"
|
||||
case .unplugged:
|
||||
return "UNPLUGGED"
|
||||
case .unknown:
|
||||
return "UNKNOWN"
|
||||
@unknown default:
|
||||
return "UNKNOWN"
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user