ViewController.swift
NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange(_:)), name: .UIDeviceBatteryLevelDidChange, object: nil)
@objc func batteryLevelDidChange(_ notification: Notification) {
self.infoLabel.text = ":\(Int(batteryLevel*100))%"
}
AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.sound, .alert, .carPlay, .badge]) { (success, error) in
}
UIDevice.current.isBatteryMonitoringEnabled = true
return true
}
为什么它在后台不起作用?