Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS

Stormy Location Manager Help

Following the Idea of single responsibility principle, I want to make Location Service as a singleton class. Which includes methods for finding current location and a method for reverse geocoding.

The problem I'm experiencing is that, CLLocationManagerDelegates does not have any completion handler. therefor when I instantiate the Location Service in the ViewDidLoad method, the app doesn't wait for the location service to get a fix.

Is there a way for me to make the app wait? Or Am I doing this all wrong.

My Idea was that when the app launches, The location service is called in the ViewDidLoad method.And wait until the location service returns a location. (Sorry for my bad English)

class LocationService: NSObject, CLLocationManagerDelegate{
    var locationManager : CLLocationManager = CLLocationManager()
    var location : CLLocation? = nil
    var gotLocation : Bool = false

    class var sharedInstance: LocationService{
        struct Static {
            static let instance: LocationService = LocationService()
        }
        return Static.instance
    }

    override init(){
        super.init()

    }

    func initLocationManager(){
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        if gotLocation == false{
            let locationArray = locations as NSArray
            if let loc = locationArray.lastObject as? CLLocation{
                self.location = loc
            }
            locationManager.stopUpdatingLocation()
            gotLocation = true
        }


    }

    func getLocation(completion:(CLLocation?)->Void){
        self.initLocationManager()
        self.locationManager.startUpdatingLocation()
        completion(self.location)
    }

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        println("error: \(error.localizedDescription)")
    }
}