Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

objective c - How to check validity of CLLocation in iOS

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~

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As Abizern's comment implies, you shouldn't assume the location will be ready to use immediately after setting showsUserLocation to YES.

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:

  • Check if userLocation.location is nil. If it is, the location hasn't been obtained yet, it failed, or showsUserLocation is NO.
  • If the location is not nil, then you can look at the coordinate property and that can be checked (if you think it might not be valid) using the CLLocationCoordinate2DIsValid 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 be nil.

This seems to happen when running an app for the first time and after setting showsUserLocation to YES. 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 is nil.


By the way, in your code you may want to set the delegate before setting showsUserLocation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...