• Detecting low Power Mode in Swift

    26 February 2016

    What is low power mode?

    Low power mode is a new way that apple is tackling their ever dwindling batteries. It stops all background activity, dims the screen and uses different assets to save power. It’s pretty neat to be fair, I have survived on 1% for half an hour before. I know, Sounds like a lie, but trust me. It isn’t.

    Create Detect Low Power Mode Project

    For this tutorial, we are going to create a basic app that will try to download a video from youtube. Not actually extract and download onto the device just load.We will detect low power mode using swift and defer the action until after the low power mode is deactivated.

    Create a new Single View Application, call it whatever you like and save it wherever you see fit.

    The first thing we need to do is declare some variables at the top. So, in your ViewController.Swift file. just under the class declaration, write:

     
    var StartVideoDownload = true
    let processInfo = NSProcessInfo.processInfo()
    

    An NSProcessInfo object is created the first time this method is invoked, and that same object is returned on each subsequent invocation.

    Now we are going to create a function that will start the download:

    func downloadStart(){
        guard let url = NSURL(string: "https://www.youtube.com/embed/YQHsXMglC9A") where
           !processInfo.lowPowerModeEnabled else{
           return
        }
    StartVideoDownload = false
    }

    Now, we are going to implement the powerModeChanged(_:) method.

     
    func powerModeChanged(notif: NSNotification){
         guard mustDownloadVideo else{
             return
         }
    downloadStart()
    }
     

    That’s it. A very simple solution to detecting low power mode in your apps and providing alternatives for downloading to the user.


Comments

Comments closed on this post.