如何检查iOS中CLLocation
的有效性?
实际上这是我的情况,
我只是创建一个新地图
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'
提前致谢〜
答案 0 :(得分:10)
正如Abizern的评论所暗示的那样,在将showsUserLocation
设置为YES
之后,您不应该认为该位置可以立即使用。
当位置可用时,地图视图将调用其委托方法didUpdateUserLocation
(如果获取位置失败,将调用didFailToLocateUserWithError
委托方法。)
在didUpdateUserLocation
方法之外,有以下几种方法可以检查位置是否可以使用:
userLocation.location
是否为nil
。如果是,则尚未获得该位置,但该位置失败,或showsUserLocation
为NO
。nil
,那么,您可以查看coordinate
属性,并且可以使用以下内容检查(如果您认为它可能无效) CLLocationCoordinate2DIsValid
功能。但请注意,坐标0,0有效(这通常发生在位置为零时)。我注意到即使在didUpdateUserLocation
委托方法中,userLocation.location
也可以是nil
。
在第一次运行应用并将showsUserLocation
设置为YES
后,似乎会发生这种情况。此时,iOS会提示用户“允许应用使用您的位置?”同时调用委托(即使用户尚未响应提示并且位置尚未确定)。
因此,在该委托方法的顶部,您还应该检查userLocation.location
是否为nil
。
顺便说一下,在您的代码中,您可能需要在设置showsUserLocation
之前设置委托。
答案 1 :(得分:6)
基于Anna K的解释,检查CLLocationCoordinate2DIsValid(YOURLOCATION)的有效性是一般的好习惯。
如果您从Web服务或SQLite数据库获得拉伸和长期,您应该在尝试向地图添加注释之前检查并确保该位置有效。以下是此操作的示例:
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];
}
对于所有遇到问题的人,如果成功地将一堆引脚添加到地图中,并且使用相同的代码尝试添加另一组引脚但应用程序崩溃,请尽快尝试。对于那些在这个例子中有类似情况但没有遇到任何问题的人,无论如何都要这样做!如果您为其提供该功能,您的用户可能会添加不正确的lat / lon组合并使应用程序崩溃。
请记住,(0,0)是一个有效的坐标,所以如果您担心这一点,请不要担心这个逻辑会删除它们。这适用于那些在地球上没有实际存在的(-200,75)类型坐标。