Handling Low Power Mode and Providing Alternatives - Multitasking - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 7. Multitasking

7.2 Handling Low Power Mode and Providing Alternatives

Problem

You want to know whether the device is in low power mode and want to be updated on the status of this mode as the user changes it.

Solution

Read the value of the lowPowerModeEnabled property of your process (of type NSProcessInfo) to find out whether the device is in low power mode, and listen to NSProcessInfoPowerStateDidChangeNotification notifications to find out when this state changes.

Discussion

Low power mode is a feature that Apple has placed inside iOS so that users can preserve battery whenever they wish to. For instance, if you have 10% battery while some background apps are running, you can save power by:

§ Disabling background apps

§ Reducing network activity

§ Disabling automatic mail pulls

§ Disabling animated backgrounds

§ Disabling visual effects

And that’s what low power mode does. In Figure 7-2, low power mode is disabled at the moment because there is a good amount of battery left on this device. Should the battery reach about 10%, the user will automatically be asked to enable low power mode.

Figure 7-2. Low power mode in the Settings app

Let’s create an app that wants to download a URL but won’t do so when low power mode is enabled. Instead, the app will defer the download until this mode is disabled. So let’s start by listening to NSProcessInfoPowerStateDidChangeNotification notifications:

override func viewDidLoad() {

super.viewDidLoad()

NSNotificationCenter.defaultCenter().addObserver(self,

selector: "powerModeChanged:",

name: NSProcessInfoPowerStateDidChangeNotification, object: nil)

downloadNow()

}

Our custom downloadNow() method has to avoid downloading the file if the device is in low power mode:

func downloadNow(){

guard let url = NSURL(string: "http://localhost:8888/video.mp4") where

!processInfo.lowPowerModeEnabled else{

return

}

//do the download here

print(url)

mustDownloadVideo = false

}

Last but not least, write the powerModeChanged(_:) method that we have hooked to our notification:

class ViewController: UIViewController {

var mustDownloadVideo = true

let processInfo = NSProcessInfo.processInfo()

func powerModeChanged(notif: NSNotification){

guard mustDownloadVideo else{

return

}

downloadNow()

}

...

See Also