Search code examples
iosswiftcllocationmanagercllocation

Location class using CLLocationManager in swift


I new to iOS. I have an app that allows the user to update their location in different view controllers. I am trying to minimize the amount of code to do this, so instead of duplicating the methods to achieve this, I put all the location related methods in a separate class.

import UIKit
import CoreLocation

class LocationUtil: NSObject, CLLocationManagerDelegate {
   let locationManager = CLLocationManager()

   func findUserLocation()->Void{
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }

from my view controller I am calling this class like so.

 override func viewDidLoad() {
        super.viewDidLoad()
        let locUtil = LocationUtil()
        locUtil.findUserLocation()

}

however, none of the delegate methods get called. When I use the same code directly in a view controller it works fine. What am I doing wrong?


Solution

  • The problem is that locUtil, to which you have assigned your LocationUtil instance, is an automatic variable — that is, it is local to the viewDidLoad function. Thus, when viewDidLoad runs, locUtil (and your LocationUtil instance) comes into existence, exists for one more line, and vanishes in a puff of smoke. Your LocationUtil instance is thus destroyed once more — taking its instance variables, such as the location manager, with it.

    Thus there is no time for anything to happen. The location manager and its delegate exist for about a millionth of a second. That is not long enough to work out your location!