Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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)")
    }
}