如何在iOS中检查CLLocation的有效性
如何检查iOS中的CLLocation
有效性?
其实这是我的情况,
我只是创build一个新的地图
mapView = [[MKMapView alloc] initWithFrame:CGRectMake(10, 30, 300, 380)]; mapView.showsUserLocation = YES; [mapView setDelegate:self];
然后我想检查用户位置的有效性
mapView.userLocation.location
由于我在使用用户位置时遇到此错误
'NSInvalidArgumentException', reason: 'Invalid Coordinate -180.00000000, -180.00000000'
在此先感谢〜
正如Abizern的评论所暗示的那样,在将showsUserLocation
设置为YES
之后,您不应该假定该位置将立即showsUserLocation
。
当位置可用时,地图视图将调用其委托方法didUpdateUserLocation
。
(如果获取位置失败,将调用didFailToLocateUserWithError
委托方法。)
在didUpdateUserLocation
方法之外,这里有几种方法来检查位置是否可以使用:
- 检查
userLocation.location
是否nil
。 如果是,位置尚未获得,则失败,或显示用户showsUserLocation
为“NO
。 - 如果位置不是
nil
, 那么您可以查看coordinate
属性,并且可以使用CLLocationCoordinate2DIsValid
函数检查(如果您认为它可能无效)。 但是请注意,坐标0,0是有效的(这通常发生在位置为零时)。
我注意到,即使在didUpdateUserLocation
委托方法中, userLocation.location
也可以nil
。
这似乎发生在第一次运行应用程序,并将showsUserLocation
设置为YES
。 那时,iOS会提示用户“允许应用程序使用您的位置?” 同时调用代理(即使用户尚未响应提示并且位置尚未确定)。
因此,在该委托方法的顶部,您还应该检查userLocation.location
是否nil
。
顺便说一下,在你的代码中,你可能需要在设置showsUserLocation
之前设置showsUserLocation
。
为了build立在Anna K的解释之上,检查CLLocationCoordinate2DIsValid(YOURLOCATION)的有效性是一个很好的习惯。
如果您从networking服务或SQLite数据库获取lats和long,则应该在尝试向地图添加注释之前检查并确保位置有效。 下面是一个例子:
for (int i = 0; i < [yourArray count]; i++) { YourOBJ *obj = [yourArray objectAtIndex:i]; yourCLLocation2D.latitude = obj.latitude; yourCLLocation2D.longitude = obj.longitude; AnnotationPin *anno = [[AnnotationPin alloc] initWithCoordinate: yourCLLocation2D]; if (CLLocationCoordinate2DIsValid(yourCLLocation2D)) { anno.lat = obj.latitude;//Maybe you want to store lat anno.lon = obj.longitude;//and lon anno.title = obj.name//define the title anno.subtitle = obj.info//and subtitle for your annotation callout anno.yourLocation = yourCLLocation2D;//Some of these aren't necessary anno.tag = i;//but can really help to define and track pins [map addAnnotation:anno]; } [anno release]; }
对于所有那些有问题的地方,你成功添加一堆地图的引脚,并使用相同的代码尝试添加另一组引脚,但应用程序崩溃,试试这个尽快。 对于那些在这个例子中有类似情况的人,但是还没有遇到任何问题,反正这样做! 您的用户可能会添加一个不正确的纬度/经度组合和崩溃的应用程序,如果你给他们的function。
请记住,(0,0)是一个有效的坐标,所以不要担心这个逻辑删除那些如果你关心的。 这是针对地球上不存在的那些(-200,75)types的坐标。