King
King

Reputation: 2035

Device Charging status Swift

I am trying to get the state of the battery in my project and set a variable to true if the device is charging. The problem I am facing now is the variable does not change irrespective of charging or not. here is my code.

 var chargingStatus: Bool? = false

 func declaration() {
        UIDevice.current.isBatteryMonitoringEnabled = true
        NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: UIDevice.batteryStateDidChangeNotification, object: nil)

    }

@objc func batteryStateDidChange(_ notification: Notification) {

        print("BATTERY STATE \(batteryState)")
        switch batteryState {
        case .unplugged, .unknown:
            chargingStatus = false
        case .charging:
            chargingStatus = true
        case .full:
            chargingStatus = false
            print("charging or full")
        }
    }

Upvotes: 0

Views: 231

Answers (1)

Enea Dume
Enea Dume

Reputation: 3232

You must use battery state nottifications UIDeviceBatteryStateDidChangeNotification and UIDeviceBatteryLevelDidChangeNotification

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryStateDidChange:", name: UIDeviceBatteryStateDidChangeNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryLevelDidChange:", name: UIDeviceBatteryLevelDidChangeNotification, object: nil)   

    // Stuff...
}

func batteryStateDidChange(notification: NSNotification){     
    // The stage did change: plugged, unplugged, full charge...
}

func batteryLevelDidChange(notification: NSNotification){     
   // The battery's level did change (98%, 99%, ...)
}

Upvotes: 1

Related Questions