Taming Core Location

In today’s mobile development environment using the device’s GPS in some shape, form or fashion is a given. Apple provides a great toolset for developers to access and utilize this functionality, but this is often done carelessly. I am not talking about privacy concerns or the misuse of the data, but many developers, myself included early on, had a poor code design implementation. The characteristics of such are usually:

  • CoreLocation implementation that was always tied directly to a particular UIViewController
  • Set the accuracy to kCLLocationAccuracyBest
  • Set filtering to kCLDistanceFilterNone.
  • Requests way to many location updates

Let’s examine each reason why these are not the best practice

Tight Coupling is Wrong

This is a more of a development practice that developers should always attempt to achieve in their code. There are always examples and uses cases as to why you would have to break this paradigm, but is still goal none the less. What we generally see, and most tutorials on the topic do this, is that the UIViewController sublcass will conform to the CLLocationManagerDelegate protocol, setup the manager and properties and listen for callbacks. I guess that is OK if you have only one use case and user interaction that requires CoreLocation, but in most cases you need to access CoreLocation more than once, thus you have to duplicate the same code. The “C” in MVC has now broken it’s intended contract and you have tightly coupled code.

Less Accuracy is More

This lesson is pretty simple. The more accurate the location you request, the longer it takes to get and the more battery power is drained. The faster the battery is drained the faster the iOS user gets pissed. The simplest example is a weather application. There is NO need to request such a detailed location. By setting your accuracy to kCLLocationAccuracyThreeKilometers you save yourself, and most importantly the user, time and end up with same information. Weather is usually shown based on a region area. i.e. zip code or city.

“For example, setting the desired accuracy for location events to one kilometer gives the location manager the flexibility to turn off GPS hardware and rely solely on the WiFi or cell radios. Turning off GPS hardware can lead to significant power savings.” – CoreLocationManager Reference

Filters are For Your Protection

Unless you are creating a turn-by-turn navigation app set a filter. Getting a location updates every half step or every second doesn’t add any value to the task of the application, but does have the same downsides as mentioned above. Poor battery life and horrible user experience.

You Don’t Need Updates Every Two Feet

This error is really an error in judgement. Apple provides developers with the fine grained control via distanceFilter and desiredAccuracy, but should be used sparingly and with apps that require multiple checks throughout the app session for location updates.

This service is most appropriate for applications that need more fine-grained control over the delivery of location events. Specifically, it takes into account the values in the desiredAccuracy and distanceFilter property to determine when to deliver new events. The precision of the standard location services are needed by navigation applications or any application where high-precision location data or a regular stream of updates is required. However, these services typically require the location-tracking hardware to be enabled for longer periods of time, which can result in higher power usage.

For apps that don’t require a constant stream of updates it is best to use start/stopMonitoringSignificantLocationChanges.

This method is more appropriate for the majority of applications that just need an initial user location fix and need updates only when the user moves a significant distance. This interface delivers new events only when it detects changes to the device’s associated cell towers, resulting in less frequent updates and significantly lower power usage.

Better CoreLocation Pattern Options

The first issue to tackle when implementing CoreLocation features is how to create your own manager that can be used and called throughout the app. The second issue that has to be addressed is how to allow other classe, regardless of type, UIView, UIViewController, NSObject, get notified of updated location information.

Issue One

The basic approach is to create subclass of NSObject that conforms to CLLocationManagerDelegate and implements the appropriate delegate methods. In my particular case I do have to listen for a stream of updates so I will be setting the desiredAccuracy and distanceFilter properties.

Issue Two

In order to tackle issue 2 I go one of three ways: NSNotification, Target/Action or KVO.

NSNotification would solve this problem, however it is seemed too decoupled and I personally feel that NSNotifications should be reserved for OS level notifications not service layer/domain model context changes. Finally, there are performance considerations when it comes to using notifications. No matter if the post to the notification center is done asynchronously or synchronously it is dispatched to the object synchronously. If there are a number of observers or if there is an instance where an observer must do a lot of work then your app could experience a significant delay.

Next on the list is the target/action pattern. While NSNotification was too decoupled from listeners, using target/action has now added a level of coupling that I felt a little unnecessary. In our custom manager class I would have to set a property, either NSMutableArray, NSSet or id that would hold the target instance, in addition, a property for the SEL, and when the location manager’s delegate method received a valid location update I would have to call something like:

`//NSMutableArray or NSSet

[clmListeners makeObjectsPerformSelector:@selector(methodToPerform)];`

`//id target

[target performSelector:@selector(methodToPerform)]`

There are two issues with doing the above proposal:

  1. You have the manager class now responsible for another class’s implementation without a contract.

  2. You are getting really close to having a delegate pattern which brings us closer to a one-to-one coupling between our classes.

The final option that we come to is Key Value Observing…which is the solution that I have gone with. Not only does it keep our manager class independent, but we also are also able to write our location code once while allowing our other classes to handle any UI or model manipulation as they see fit…independent of any other implementation or logic.

Custom Core Location Manager Class

gist.github.com/2421914

View Controller Observing Change to Current Location

gist.github.com/2421928

Forward Geocoding in iOS4 and iOS5

Forward Geocoding

It is a common scenario that every developer has run into.

Locate places near me based upon a particular address and/or zip code.

In order to get the correct results the address needs to be converted to a lat/long coordinate. With iOS5 Apple has provided us with CLGeoCoder class which has convience methods for reverse/forward geocoding. Unfortunately, there isn’t really any built-in functionality for iOS4. Most current apps still have to support iOS4 so what are developers doing to fill the gap? Write their implementations for multiple OS support. Below is what I use.

** Note: I did use Sergio Martínez-Losa Del Rincón article as a starting point for the iOS4 support.

Techniques

  • Google’s Map API
  • CLGeoCoder
  • Objective-C blocks for callback
  • Grand Central Dispatch

Implementation

iOS5

I tackled the easiest solution first. Utilizing iOS5’s CLGeoCoding geocodeAddressString:completionHandler: . However, when I first use the method I kept getting back a location of {0.0,0.0} in my log. The reason being that I was neglecting the fact that the method executes asynchronously and doesn’t return its value. Hmmm….

Not too much of a hurdle thanks to the implementation of block handling. By adding a completionHandler to my own method I was able to provide a callback with the appropriate coordinate that I need after the request had finished.

iOS4

Duplicating the ease of the iOS5 functionality was a bit more involved. I created a category method on NSString (see the above referenced article for code origin. I did make updates to it.) for making a call to the Google Maps API and return their forward coding result. The method itself isn’t asynchronous because I wanted to leave the decision of whether or not to call the method async or sync up to the developer. To provide asynchrous support was easy just by utiliizing GCD.

Decision Time

Deciding which code block should the calling method execute was the final task to finish. Once again this was extremely simple.

if (NSClassFromString(@“CLGeocoder”)) { // ios5 } else { // everything else. in this case we are assuming there isn’t support for iOS3.x }

Code

Turn by Turn Directions with MapKit and Google Maps

Update - 03.31.2010

I decided that I didn't like the accuracy of the location from the browser.  It is isn't as good as the MapKit or default Google Maps app on the phone.  I added a button the directions page to open default maps application.

One of the best features used in Google Maps is the turn-by-turn directions.  Unfortunately, I haven't seen, and don't even know if it exists without proprietary code, an effective way to show turn-by-turn directions using the MapKit API in the iPhone SDK.  Though Google announced that they have included it in their Android platform they were vague about if/when it might come to the iPhone SDK.  No matter, where there is CoreLocation there is a way.

Goal
Most smaller companies only have one "brick and mortar" location.  So I wanted to show that location on the map and then present the user with ability to get turn by turn directions to their location.  In my example app the marker will show the location of my favorite sushi place in Memphis, Sekisui's Pacific Rim.

Obstacles
No clear way to implement turn-by-turn directions with MapKit using the iPhone SDK.  Though Safari for the iPhone has the ability to get your current location via the browser, i wasn't very impressed with it's accuracy.

Solution
Use CoreLocation to get the user's lat/long and then pass that to a UIWebView that will display a Google Map with directions.  Though in this example I am using a local html that is stored on the phone a better implementation would be to have the file stored remotely and then cached on the user's phone for faster load time.  However, it is important to note that you should "decache" the file if the user's previous coordinates are different then their new current location.

Note
For the best results and accuracy it is better to run this on your device since CoreLocation the simulate will show Apple's headquarters as the user's location.