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