SixtyDegreesNorth SixtyDegreesNorth - 16 days ago 8
Swift Question

Handler doesn’t receive batteryState notifications

My batteryStateDidChange handler never gets called (on either Simulator or iPhone). I’ve found several examples (usually old) on this site and I’ve been through the Apple documentation. I also get the pid error: “cannot attach to process due to System Integrity Protection” when I build but not sure if this would be the cause. Although I’ve been programming since the 1970’s, I’ve never used Swift or Xcode before. I’m using Swift 4 and Xcode 9.1. Help would be appreciated.

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

//Tell UIDevice that we want battery notifications
UIDevice.current.isBatteryMonitoringEnabled = true

// Register to listen for notifications
NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange(_notification:)), name: Notification.Name.UIDeviceBatteryStateDidChange, object: nil)

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

var batteryState: UIDeviceBatteryState {
return UIDevice.current.batteryState
}

// Handle the batteryStateDidChange notification <---- This never gets called
@objc func batteryStateDidChange(_notification: Notification) {
switch batteryState {
case .unplugged, .unknown:
print("not charging")
case .charging, .full:
print("charging or full")
}
}
}

Answer Source

There must be a space character after the underscore

@objc func batteryStateDidChange(_ notification: Notification)

and the selector is simply

#selector(batteryStateDidChange)