Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difficult to get iOS thermal state monitoring to report notifications

Tags:

ios

swift

Apple has a 2019 WWDC session on thermal state monitoring: https://developer.apple.com/videos/play/wwdc2019/422/

And the docs show an example of registering for a notification here: https://developer.apple.com/library/archive/documentation/Performance/Conceptual/power_efficiency_guidelines_osx/RespondToThermalStateChanges.html

I could not get the notification to appear. I used the Devices and Simulators in Xcode where you select the device then at the bottom you can select Thermal State in Device Conditions. When I set to serious, it did not get a notification even after registering.

like image 730
D. Rothschild Avatar asked Nov 18 '25 19:11

D. Rothschild


1 Answers

This answer worked for me.

I ended up creating a singleton class and then it started working. Here is the class.

To use this, remember to import Combine. Also, the logging here (DDLogInfo(...) is from CococaLumberjackSwift so take out those statements if you are not using it.

class ThermalMonitor {
  
  // MARK: - Singleton

  static let sharedInstance = ThermalMonitor()
  
  var cancelBag = [AnyCancellable]()
  
  init() {
    registerForThermalNotifications()
  }
  
  private func registerForThermalNotifications() {

    let thermalState = ProcessInfo.processInfo.thermalState.rawValue
    DDLogInfo("THERMAL: Thermal state on launch is (note 0 is nominal): \(thermalState)")
    
    NotificationCenter
      .Publisher(center: .default, name: ProcessInfo.thermalStateDidChangeNotification)
      .sink { [weak self] (notification) in
        self?.responseToHeat(notification)
        }
      .store(in: &cancelBag)
  
    DDLogInfo("THERMAL: Did start thermal monitoring")
  }
  
  @objc private func responseToHeat(_ notification: Notification ) {
    let state = ProcessInfo.processInfo.thermalState
    switch state {
    case .nominal:
      DDLogInfo("THERMAL: Thermal state is nominal (0).  No action needed.")
    case .fair:
      DDLogInfo("THERMAL: Thermal state is fair (1).  Device is starting to heat up. Reduce expensive CPU operations.")
    case .serious:
      DDLogInfo("THERMAL: Thermal state is SERIOUS (2).  Time to reduce CPU usage and device charging.")
    case .critical:
      DDLogInfo("THERMAL: Thermal state is CRITICAL (3).  Cool down the device NOW.")
    @unknown default:
      DDLogInfo("THERMAL: Thermal state is UNKNOWN.")
    }
  }
  
}
like image 153
D. Rothschild Avatar answered Nov 21 '25 08:11

D. Rothschild



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!