我正在使用以下代码获得无限循环。当用户点击“getDirections”方法按钮时,警报会正确触发。当从警报按钮中选择“获取Drections”时,谷歌地图可以完美地运行。当他们重新打开应用程序时,它会打开这个视图,应用程序会立即返回谷歌地图,再次重新运行该方法。我唯一能阻止这种情况就是让“应用程序不在后台运行”转为YES,我不想这样做。
有人能告诉我为什么会这样吗?
-(IBAction)getDirections
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Directions" message:@"Do you want driving directions?" delegate:self cancelButtonTitle:@"No Thanks" otherButtonTitles:@"Get Directions", nil];
[alert show];
[alert release];
}
-(void)showDirections
{
locationManager = [[CLLocationManager alloc] init];
[locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
[locationManager setDelegate:self];
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
CLLocationCoordinate2D coord = [newLocation coordinate];
NSArray *array = [dataHold objectForKey:@"Subtree"];
NSString *latitude = [NSString stringWithFormat:@"%@",[array objectAtIndex:4]];
NSString *longitude = [NSString stringWithFormat:@"%@",[array objectAtIndex:5]];
double clubLatitude = [latitude doubleValue];
double clubLongitude = [longitude doubleValue];
urlString = [NSString stringWithFormat:@"http://maps.google.com/?saddr=%1.6f,%1.6f&daddr=%1.6f,%1.6f", coord.latitude, coord.longitude, clubLatitude, clubLongitude];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
buttonString = [alertView buttonTitleAtIndex:buttonIndex];
if([buttonString isEqualToString:@"Get Directions"] )
{
[self showDirections];
buttonString = nil;
}
else if( [buttonString isEqualToString:@"No Thanks"] )
{
nil;
}
}
答案 0 :(得分:2)
{cc} didUpdateToLocation
CLLocationManager startUpdatingLocatoin
委托方法。
因此,每次更新位置时都会调用didUpdateToLocation
内的代码 - 即使您从后台启动应用程序也是如此。
并且该方法被调用很多,具体取决于您的locationManager的distanceFilter
属性。您可以通过向委托方法添加NSLog
语句来确认这一点,并查看它被调用的次数。
关于该方法的文件:
讨论此方法的实现是可选的。你应该 但是,实现这个方法。
当此消息传递给您的代理时,新的 位置数据也可以直接从CLLocationManager获得 宾语。 newLocation参数可能包含缓存的数据 从之前使用的位置服务。你可以使用 location对象的timestamp属性,用于确定最近的位置 位置数据是。
遵循该指南并在didUpdateToLocation方法中保存timeStamp(或任何其他类型的标识符)。
设置timeStamp后,您可以使用这些值显示Google地图。旁注:您的CLLocationManager有一个属性location
,每次调用didUpdateToLocation
时都会获得更新 - 因此您可以依赖该属性来获取代码中其他位置的当前位置。
HTH
答案 1 :(得分:2)
您缺少以下代码。你应该把它添加到 (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation method
[locationManager stopUpdatingLocation];