Search code examples
iosswiftswift5

Add new locations to an array Swift


I'm trying to add locations to an array so I can calculate the cumulative distance but I'm stuck on how to actually add these to my own array, it's just returning the same location all the time. It calculates the distance fine (I've tested with hard coded locations) and I think I'm calling startUpdatingLocations properly so not sure what the problem is, I've tried various ways of trying to add to the array but now I'm getting No exact matches in call to instance method 'append' :

class RaceViewController: UIViewController, CLLocationManagerDelegate {

var locations : [CLLocation] = []
var locationManager: CLLocationManager!

override func viewDidLoad() {
    super.viewDidLoad()
    if (CLLocationManager.locationServicesEnabled())
           {
               locationManager = CLLocationManager()
               locationManager.delegate = self
               locationManager.desiredAccuracy = kCLLocationAccuracyBest
               locationManager.requestAlwaysAuthorization()
           }
       }

@IBAction func trackPressed(_ sender: UIButton) {
    
    locationManager.startUpdatingLocation()
    print(totalDistance(of: locations))
    print(locations)
    print(locationManager.location)
}

//get total distance between locations
func totalDistance(of locations: [CLLocation]) -> CLLocationDistance {
    var distance: CLLocationDistance = 0.0
    var previousLocation: CLLocation?
    
//trying here to add the location to the array of locations as and when it updates
    locations.append(contentsOf: locationManager.location)
    
    locations.forEach { location in
        if let previousLocation = previousLocation {
            distance += location.distance(from: previousLocation)
        }
        previousLocation = location
    }
    
    return distance
}

}


Solution

  • You use (contentsOf: which appends array not item , so Replace

    locations.append(contentsOf: locationManager.location)
    

    With

    locations.append(locationManager.location) // recommended 
    

    Or

    locations.append(contentsOf: [locationManager.location]) // not recommended