0

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
}

Why it does not work in background?

user1951072
  • 65
  • 1
  • 6
  • 2
    Why would it work? Your app it is not downloading, fetching data, updating location or anythink listed in the Background mode capabilities – Leo Dabus Oct 26 '17 at 07:31
  • @Leo Dabus But I am testing the app on my real iPhone now. When I run the app then lock the screen it works fine. But when I run other app it doesn’t work. There’s no notification anymore – user1951072 Oct 26 '17 at 08:07
  • 1
    To save energy, iOS does not keep apps running in the background like they would on a desktop system. Beyond a few seconds after going to background, and some specific situations, the app is suspended, and doesn’t run or receive notifications of this kind. – jcaron Oct 26 '17 at 14:16

0 Answers0