Hokkaido Hokkaido - 6 months ago 42
Swift Question

mapView.annotations.count is not 0 in swift

I have the following code:

@IBAction func countAnnotations(sender: AnyObject) {
print("Annotations Count = \(mapView.annotations.count)")

if mapView.annotations.count == 0 {
print("No annotations")
}else{
print("1 or more annotations")
}
}


This is meant to check how many annotations are on my map view.

The issue arises when I start retrieving the user location using the following code:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//Update the current location
currentLocation = manager.location!.coordinate
print("locations = \(currentLocation.latitude) \(currentLocation.longitude)")
}


For some reason this seems to count as an annotation. How do I actually detect if an actual annotation is placed?

Answer

Fixed by simply adding a currentLocationVisible = false bool variable. Then setting it and checking it.

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
      //Update the current location
      currentLocation = manager.location!.coordinate
      print("locations = \(currentLocation.latitude) \(currentLocation.longitude)")
      currentLocationVisible = true
}

Now its simply about checking the variable.

if (mapView.annotations.count == 0 || currentLocationVisible == true)

Easy as that!