I have multiple view controllers that need to get the user's location, so I wanted to create a separate class that the ViewControllers can call to get the user's latest location.
locationManager:didUpdateToLocation:fromLocation returns void. How do I pass the latitude and longitude data back to my ViewControllers as soon as the user's latitude and longitude is calculated?
I could try writing getters and setters in my locationManaging class, but if I do that, how do I know when to call the latitude getter and longitude getter methods from my ViewController class? How do I hold the ViewController's main thread to wait for the latitude and longitude values from the locationManaging class?
Thanks!
Create a singleton class which has a
latitude
andlongitude
properties,startLocating
andendLocating
. In the class, create aCLLocationManager
instance, and set its delegate to be the singleton. InstartLocating
andendLocating
, call the appropriate methods of theCLLocationManager
instance. Make the delegate methods update thelatitude
andlongitude
properties. In otherViewControllers
, read this singleton'slatitude
andlongitude
properties.To know when to read those properties from another
ViewController
, set an observer on these properties (see the NSKeyValueObserving Protocol ReferenceBefore doing this, look up the Internets for existing code.
After doing this, upload it to GitHub with a permissive license.
In the process of learning to obtain user location in a singleton class, I downloaded this code https://github.com/irfanlone/CLLocationManager-Singleton-Swift. After foddleing with it to make in run on Xcode8.3.3 Swift 3, I cannot get any output in the debug console. In fact I can't even get this location autherization dlalog to display. I suspect the data from the singleton is not passed to the view controller, but I cannot fine the solution, can you see what is wrong? Thanks.
The corrected code for Swift 3 is:
Based on the above answers, here is what I did and you can find the complete example on github https://github.com/irfanlone/CLLocationManager-Singleton-Swift
Just import this file in your project, then you can either choose to implement the LocationUpdateProtocol or listen to notification for location updates
Usage:
As user1071136 said, a singleton location manager is probably what you want. Create a class, a subclass of NSObject, with just one property, a
CLLocationManager
.LocationManagerSingleton.h:
LocationManagerSingleton.m:
To get the most recently received location, simply use
[LocationManagerSingleton sharedSingleton].locationManager.location
. It might take a few seconds to warm up the GPS to get accurate locations.Here's what I did when implementing a location manger singleton in swift. It's based on user1071136's strategy, as well as this swift pattern.