Ernestina Juan Ernestina Juan - 5 months ago 23
Swift Question

iOS - Swift - Callback when phone gets plugged in

I have an Android app which uses a BroadcastReceiver for older versions of Android and a JobScheduler-based implementation for Android 5.0+ which starts my app automatically when the phone gets connected to the charger (namely, it executes an IntentService to process some files).

I want to be able to do the same on iOS (in Swift). I have found very little searching on Google and this site, I think maybe NSNotificationCenter is related to this, but still I don't know.

So, is there an equivalent to this on iOS?

Thank you.

Answer

In iOS, we don't have the same device-level access at all times like we would in Android. Our applications can only receive notifications like the battery state when they haven't been terminated.

When your application has the foreground, try using the code below to access the device's battery state.

// Begins battery state monitoring //
UIDevice.currentDevice().batteryMonitoringEnabled = true
// Check for battery's current status //
if (UIDevice.currentDevice().batteryState != .Unplugged) {
    print("Device is plugged in.")
}

You could also run the following code to check the device's battery state at set times when your application reaches the background. NOTE - Doing the following will most likely get you declined from an App Store release.

func applicationDidEnterBackground(application: UIApplication) {
    // Begins battery state monitoring //
    UIDevice.currentDevice().batteryMonitoringEnabled = true
    // Schedules NSTimer with intervals of 10 seconds //
    NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(batteryCheck), userInfo: nil, repeats: true)
}

func batteryCheck() {
    if (UIDevice.currentDevice().batteryState != .Unplugged) {
        print("Device is charging.")
    } else {
        print("Device is NOT charging.")
    }
}
Comments