Search code examples
swiftxcodeswift3cllocationmanager

I am trying to get updates on location with a set interval in Swift 3, but it runs my function a lot of times each interval, it should only run once


I am getting location of the user with locationManager.startUpdatingLocation() which then calls a function that handles all my logic, problem is it seems to get called multiple times and I can't figure out why.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let locValue:CLLocationCoordinate2D = manager.location!.coordinate
    print("locations = \(locValue.latitude) \(locValue.longitude)")

    long = locValue.longitude
    lat = locValue.latitude

    if(self.arrayOfCellData.count > 0)
    {

        for i in 0...self.arrayOfCellData.count-1
        {
            getdistance(lat0: self.arrayOfCellData[i].shop.latitude!, long0: self.arrayOfCellData[i].shop.longitude!, lat1: locValue.latitude, long1: locValue.longitude)
            {distance in

                self.arrayOfCellData[i].meterstolocation = distance
            }
        }
        DispatchQueue.main.async {
            self.myTable.reloadData()
        }
    }
    print("stopped updating")
    locationManager.stopUpdatingLocation()
}

var run: Bool = true;

func updateLocations()
{
    if(run)
    {
        run = false;
    }
    else
    {
        locationManager.startUpdatingLocation()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
//

    locationManager.requestAlwaysAuthorization()
    //
    //
    //
    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.pausesLocationUpdatesAutomatically = false
        locationManager.startUpdatingLocation()

        Timer.scheduledTimer(timeInterval: 10,
                             target: self,
                             selector: #selector(self.updateLocations),
                             userInfo: nil,
                             repeats: true)
    }

my output is:

locations = 37.33228724 -122.05833354
stopped updating
locations = 37.33228724 -122.05833354
stopped updating
locations = 37.33228724 -122.05833354
stopped updating
locations = 37.33228724 -122.05833354
stopped updating
locations = 37.33228724 -122.05833354

the output itself is correct, but it spits out multiple prints in one go. And I do not want the code to be run multiple times, only once per interval.


Solution

  • You should not call locationManager.stopUpdatingLocation() after you get a location, and you do not need the timer. Just call locationManager.startUpdatingLocation() once at the start and it will keep sending you updates automatically but only when the location changes. See the documentation at https://developer.apple.com/reference/corelocation/cllocationmanager