How to check validity of CLLocation
in iOS?
In fact this is my situation,
I just create a new map
mapView = [[MKMapView alloc] initWithFrame:CGRectMake(10, 30, 300, 380)];
mapView.showsUserLocation = YES;
[mapView setDelegate:self];
And then I want to check the validity of the user location
mapView.userLocation.location
Since I get this error when using the user location
'NSInvalidArgumentException', reason: 'Invalid Coordinate -180.00000000, -180.00000000'
Thanks in advance~
To build on Anna K's explanation, it's general good practice to check the validity of a CLLocationCoordinate2DIsValid(YOURLOCATION).
If you are getting lats and longs from a web service or a SQLite database, you should check and make sure the location is valid before trying to add an annotation to the map. Here's an example of this in action:
For all those who are having problems where you add a bunch of pins to a map successfully, and with the same code try to add another set of pins but the app crashes, try this asap. For those who have a similar situation in this example, but haven't ran into any problems, do this anyway! Your users might add an incorrect lat/lon combo and crash the app if you give them that functionality.
Remember, (0,0) is a valid coordinate, so don't worry about this logic removing those if you are concerned about that. This is for those (-200,75) type coordinates that don't physically exist on planet Earth.
As Abizern's comment implies, you shouldn't assume the location will be ready to use immediately after setting
showsUserLocation
toYES
.When the location is available, the map view will call its delegate method
didUpdateUserLocation
.(If getting the location fails, the
didFailToLocateUserWithError
delegate method will be called.)Outside of the
didUpdateUserLocation
method, here are a couple of ways to check if the location is ok to use:userLocation.location
isnil
. If it is, the location hasn't been obtained yet, it failed, orshowsUserLocation
isNO
.nil
, then you can look at thecoordinate
property and that can be checked (if you think it might not be valid) using theCLLocationCoordinate2DIsValid
function. Note however that coordinate 0,0 is valid (this generally happens when location is nil).I have noticed that even in the
didUpdateUserLocation
delegate method,userLocation.location
can benil
.This seems to happen when running an app for the first time and after setting
showsUserLocation
toYES
. At that point, iOS prompts the user with "Allow app to use your location?" while at the same time the delegate is called (even though the user hasn't yet responded to the prompt and the location hasn't been determined).So at the top of that delegate method, you should also check if
userLocation.location
isnil
.By the way, in your code you may want to set the delegate before setting
showsUserLocation
.