Search code examples
swiftcllocationmanagerlocationmanager

Minimize HTTP requests made to my server when using LocationManager


In the code below, I'm using LocationManager to get the user's current zipCode and then I make an HTTP request to my own server to get some data based on the user's zipCode. My issue is that my code below makes an HTTP request everytime locationManager is called, usually three times per call. Ideally I would like to make the HTTP request only once the last placemark is found.

How can I minimize the HTTP requests made to my own server?

override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)-> Void in
        if error != nil {
            //AlertView to show the ERROR message
        }
        if placemarks!.count > 0 {
            let placemark = placemarks![0]
            var zipCode = placemark.postalCode ?? ""
            makeHTTPRequest(zipCode) // this is called 3 times
            self.locationManager.stopUpdatingLocation()

        }else{
            print("No placemarks found.")
        }
    })
}

Solution

  • The problem with your code is that there are probably multiple calls to locationManager(_:didUpdateLocations:) stacked up by the time you do self.locationManager.stopUpdatingLocation(). To solve that:

    • Define a global variable var didFindZipCode: Bool = false.
    • Add guard didFindZipCode == false else { return } at the beginning of the if block in which you check for number of placemarks.
    • Set didFindZipCode = true right after the guard statement.

    Just remember to set didFindZipCode to false whenever you want to start updating the location again.