9 min read

This article is written by Cecil Costa, the author of the book, Swift Cookbook. We’ll delve into what profiling is and how we can profile an app by following some simple steps.

It’s very common to hear about issues, but if an app doesn’t have any important issue, it doesn’t mean that it is working fine. Imagine that you have a program that has a memory leak, presumably you won’t find any problem using it for 10 minutes. However, a user may find it after using it for a few days. Don’t think that this sort of thing is impossible; remember that iOS apps don’t terminate, so if you do have memory leaks, it will be kept until your app blows up.

Performance is another important, common topic. What if your app looks okay, but it gets slower with the passing of time? We, therefore, have to be aware of this problem. This kind of test is called profiling and Xcode comes with a very good tool for realizing this operation, which is called Instruments.

In this instance, we will profile our app to visualize the amount of energy wasted by our app and, of course, let’s try to reduce it.

(For more resources related to this topic, see here.)

Getting ready

For this recipe you will need a physical device, and to install your app into the device you will need to be enrolled on the Apple Developer Program. If you have both the requirements, the next thing you have to do is create a new project called Chapter 7 Energy.

How to do it…

To profile an app, follow these steps:

  1. Before we start coding, we will need to add a framework to the project. Click on the Build Phases tab of your project, go to the Link Binaries with Libraries section, and press the plus sign.

    Swift Cookbook

  2. Once Xcode opens a dialog window asking for the framework to add, choose CoreLocation and MapKit.
  3. Now, go to the storyboard and place a label and a MapKit view. You might have a layout similar to this one:

    Swift Cookbook

  4. Link the MapKit view and call it just map and the UILabel class and call it
    just label:
       @IBOutlet var label: UILabel!
       @IBOutlet var map: MKMapView!
  5. Continue with the view controller; let’s click at the beginning of the file to add the core location and MapKit imports:
    import CoreLocation
    import MapKit
  6. After this, you have to initialize the location manager object on the viewDidLoad method:
       override func viewDidLoad() {
           super.viewDidLoad()
           locationManager.delegate = self
           locationManager.desiredAccuracy = 
             kCLLocationAccuracyBest        locationManager.requestWhenInUseAuthorization()        locationManager.startUpdatingLocation()    }
  7. At the moment, you may get an error because your view controller doesn’t conform with CLLocationManagerDelegate, so let’s go to the header of the view controller class and specify that it implements this protocol. Another error we have to deal with is the locationManager variable, because it is not declared. Therefore, we have to create it as an attribute. And as we are declaring attributes, we will add the geocoder, which will be used later:
    class ViewController: UIViewController, 
    CLLocationManagerDelegate {    var locationManager = CLLocationManager()    var geocoder = CLGeocoder()
  8. Before we implement this method that receives the positioning, let’s create another method to detect whether there was any authorization error:
       func locationManager(manager: CLLocationManager!,
          didChangeAuthorizationStatus status: 
             CLAuthorizationStatus) {            var locationStatus:String            switch status {            case CLAuthorizationStatus.Restricted:                locationStatus = "Access: Restricted"               break            case CLAuthorizationStatus.Denied:                locationStatus = "Access: Denied"                break            case CLAuthorizationStatus.NotDetermined:                locationStatus = "Access: NotDetermined"               break            default:                locationStatus = "Access: Allowed"            }            NSLog(locationStatus)    }
  9. And then, we can implement the method that will update our location:
       func locationManager(manager:CLLocationManager, 
         didUpdateLocations locations:[AnyObject]) {        if locations[0] is CLLocation {            let location:CLLocation = locations[0] as
                 CLLocation            self.map.setRegion(
                 MKCoordinateRegionMakeWithDistance(
               location.coordinate, 800,800),
                 animated: true)                       geocoder.reverseGeocodeLocation(location,
                 completionHandler: { (addresses,
                 error) -> Void in                    let placeMarket:CLPlacemark =
                         addresses[0] as CLPlacemark                let curraddress:String = (placeMarket.
                     addressDictionary["FormattedAddressLines"
                     ] as [String]) [0] as String                    self.label.text = "You are at
                         (curraddress)"            })        }    }
  10. Before you test the app, there is still another step to follow. In your project navigator, click to expand the supporting files, and then click on info.plist. Add a row by right-clicking on the list and selecting add row.
  11. On this new row, type NSLocationWhenInUseUsageDescription as a key and on value Permission required, like the one shown here:

    Swift Cookbook

  12. Now, select a device and install this app onto it, and test the application walking around your street (or walking around the planet earth if you want) and you will see that the label will change, and also the map will display your current position.
  13. Now, go back to your computer and plug the device in again. Instead of clicking on play, you have to hold the play button until you see more options and then you have to click on the Profile option.

    Swift Cookbook

    The next thing that will happen is that instruments will be opened; probably, a dialog will pop up asking for an administrator account. This is due to the fact that instruments need to use some special permission to access some low-level information.

    Swift Cookbook

  14. On the next dialog, you will see different kinds of instruments, some of them are OS X specific, some are iOS specific, and others are for both. If you choose the wrong platform instrument, the record button will be disabled. For this recipe, click on Energy Diagnostics.

    Swift Cookbook

  15. Once the Energy Diagnostics window is open, you can click on the record button, which is on the upper-left corner and try to move around—yes, you need to keep the device connected to your computer, so you have to move around with both elements together—and do some actions with your device, such as pressing the home button and turning off the screen. Now, you may have a screen that displays an output similar to this one:

    Swift Cookbook

Now, you can analyze who is spending more energy on you app. To get a better idea of this, go to your code and replace the constant kCLLocationAccuracyBest with kCLLocationAccuracyThreeKilometers and check whether you have saved some energy.

How it works…

Instruments are a tool used for profiling your application. They give you information about your app which can’t be retrieved by code, or at least can’t be retrieved easily. You can check whether your app has memory leaks, whether it is loosing performance, and as you can see, whether it is wasting lots of energy or not.

In this recipe we used the GPS because it is a sensor that requires some energy. Also, you can check on the table at the bottom of your instrument to see that Internet requests were completed, which is something that if you do very frequently will also empty your battery fast.

Something you might be asking is: why did we have to change info.plist? Since iOS 8, some sensors require user permission; the GPS is one of them, so you need to report what is the message that will be shown to the user.

There’s more…

I recommend you to read the way instruments work, mainly those that you will use. Check the Apple documentation about instruments to get more details about this (https://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/InstrumentsUserGuide/Introduction/Introduction.html).

Summary

In this article, we looked at all the hows and whats of profiling an app. We specifically looked at profiling our app to visualize the amount of energy wasted by our app. So, go ahead to try doing it.

Resources for Article:


Further resources on this subject:


LEAVE A REPLY

Please enter your comment!
Please enter your name here