Skip to content

Commit

Permalink
ios: fix isLowerPowerModeEnabled deadlock crash (#94)
Browse files Browse the repository at this point in the history
  • Loading branch information
Augustyniak authored Nov 1, 2024
1 parent f99fb64 commit 1c77b4a
Showing 1 changed file with 27 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,36 @@ import Foundation
import UIKit

final class LowPowerStateProvider {
private let processInfo = ProcessInfo.processInfo
private let isLowerPowerModeEnabled = Atomic(ProcessInfo.processInfo.isLowPowerModeEnabled)

init() {
// Accessing `ProcessInfo.processInfo.isLowPowerModeEnabled` frequently causes occasional crashes
// on iOS 15 (up to at least version 15.2). To reduce these calls, subscribe to
// `NSProcessInfoPowerStateDidChange` notifications and track the state of `isLowPowerModeEnabled`
// locally. This minimizes the number of `ProcessInfo.processInfo.isLowPowerModeEnabled` calls here
// to one.
NotificationCenter
.default
.addObserver(
self,
selector: #selector(powerStateDidChange(_:)),
name: Notification.Name.NSProcessInfoPowerStateDidChange,
object: nil
)
}

@objc
private func powerStateDidChange(_ userInfo: Any) {
self.isLowerPowerModeEnabled.update { $0 = ProcessInfo.processInfo.isLowPowerModeEnabled }
}

deinit {
NotificationCenter.default.removeObserver(self)
}
}

extension LowPowerStateProvider: ResourceSnapshotProvider {
func makeSnapshot() -> ResourceSnapshot? {
return LowPowerStateSnapshot(lowPowerModeEnabled: self.processInfo.isLowPowerModeEnabled)
return LowPowerStateSnapshot(lowPowerModeEnabled: self.isLowerPowerModeEnabled.load())
}
}

0 comments on commit 1c77b4a

Please sign in to comment.