CLLocationManager Singleton

CLLocationManager is a tricky business. It is easy to implement if you have only one controller interested in getting users location. It gets a bit trickier when users location needs to be shared between multiple controllers. One way of tackling this problem is to create an instance of the CLLocationManager in your AppDelegate and then share it between interested view controllers. This approach works OK, but at times can be hard to maintain.

There is a better way to accomplish this in my opinion. This approach takes advantage of singleton pattern. As you can see below, it is very simple to implement. It also offers 2 advantages:

  1. Less code.
  2. It’s much clearer where the instance is coming from which makes it so much easier to manage.

Here is how you would implement it. First, create a new class called LocationController. You can call it whatever you want actually, but LocationController makes good sense in this case.

Then implement:

To use this class, you do the usual stuff. Import the LocationController class, and (usually) in viewWillAppear: do the following:

Make sure to stop updating location in viewWillDisappear:.

You are all set. Pretty simple and clean. Hope this helps.

CLLocationManager Singleton

5 thoughts on “CLLocationManager Singleton

  1. Roberto Briones says:

    Thanks! But there is an error in the following lines:

    dispatch_once(&onceToken, ^{

    sharedController = [[self alloc]init];


    It is correct? Or why I’am getting this errors?

    1. alextheukrainian says:

      You’re getting the error because you copy-pasted code from HTML page and the ampersand (&) got pasted as &. Change that back to ampersand and you’re good.

  2. alextheukrainian says:

    This is nice, thanks. One thing: it should not be a UIViewController subclass. UIViewController isn’t meant to be used as a singleton, and a generic LocationManager shouldn’t be dealing with views. You’d use this singleton in view controllers and whatever else needs it, but the singleton itself needs not be in any way connected to UIKit.

Leave a Reply

Your email address will not be published. Required fields are marked *