Search code examples
iosswiftalamofire

POST of Location data to server recieving multiple entries


I have an iPhone app that uses AlamoFire to send Longitude / Latitude to a server. The data is sent from the app when a button is pushed. Everything is working great except that the server is receiving multiple entries of the same data from one action. I can see this in the emulator output as well as in the server. Also it seems random, sometimes 3 entries, 2 or just 1. Using swift 2.0, here is the code:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print("inside didUpdateLocations", terminator: "")

    let latestLocation = locations.last
    let coords = latestLocation!.coordinate
    print("Latitude: " + coords.latitude.description + " Longitude: " + coords.longitude.description, terminator: "")

    locationManager.stopUpdatingLocation()

    // **UPDATED HERE**
    locationManager.delegate = nil

    let recievedData : CLLocation! = nil

    if recievedData == nil {
    sendDatatoServer(coords.longitude, latitude: coords.latitude, date: dateString)
}}  // **End UPDATE**

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    print("Error while updating location: " + error.localizedDescription, terminator: "")
}
@IBAction func findMyLocation(sender:AnyObject) {
    print("inside findMyLocation", terminator: "")
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
}
// send the longitude, latitude, and date to the database server
func sendDatatoServer(longitude: Double!, latitude: Double!, date: String!) {
    print("inside sendDataToServer", terminator: "")
    Alamofire.request(.POST, "http://example.com", parameters:["latitude": latitude, "longitude": longitude, "date": date])
}

Output from xcode:

inside findMyLocation * inside didUpdateLocations * Latitude: -26.204103 Longitude: 28.0473051inside sendDataToServer * 
inside didUpdateLocations * Latitude: -26.204103 Longitude: 28.0473051inside sendDataToServer * 
inside didUpdateLocations * Latitude: -26.204103 Longitude: 28.0473051inside sendDataToServer * 

From the database:

ID: 622 ---> Longitude: 28.0473. Latitude: -26.2041. Date: 2015-10-08 10:04 AM

ID: 623 ---> Longitude: 28.0473. Latitude: -26.2041. Date: 2015-10-08 10:04 AM

ID: 624 ---> Longitude: 28.0473. Latitude: -26.2041. Date: 2015-10-08 10:04 AM

In this particular POST, it sent 3 times. From the xcode output it looks to be from the didUpdateLocations but i don't understand why.


Solution

  • After you stop updating your location you should also set the delegate to nil. This will prevent any future calls to the delegate until you set it again.

    I would also recommend putting some checks around your location before calling the post method to ensure you have a valid location.