我正在玩CLLocation类。我成功完成了以下代码。当我按下一个按钮时,它会在ALert msg中显示该位置。当我再次单击相同的按钮时,位置显示错误。而且我也注意到eveytime我必须去设置 - 隐私 - 位置服务,以便每次都能访问。当应用程序正确显示当前位置时,iPhone设置中的位置访问将变为空白。再次,我必须将其设置为始终运行应用程序。我没有在.plists中添加任何内容。我刚刚写了下面的代码。我的问题是,在将位置压力设置为始终
后,它仅显示正确的位置-(CLLocationCoordinate2D) getLocation{
CLLocationCoordinate2D coordinate;
if ([CLLocationManager locationServicesEnabled])
{
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
coordinate = [location coordinate];
}
return coordinate;
}
- (void)startTimer {
// if ([Run isEqualToString:@"can"]) {
i++;
NSLog(@"the i value %d", i);
Run =@"cant";
CLLocationCoordinate2D coordinate = [self getLocation];
CLGeocoder *ceo = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude]; //insert your coordinates
[ceo reverseGeocodeLocation:loc
completionHandler:^(NSArray placemarks, NSError error)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSDictionary *eventLocation = [NSDictionary dictionaryWithObjectsAndKeys:placemark.name,@"NAME",placemark.subLocality,@"SUBLOCALITY" ,placemark.postalCode,@"POSTALCODE" ,nil];
LocationDetails= [NSMutableDictionary dictionaryWithObjectsAndKeys:eventLocation,@"value", nil];
NSString *name=placemark.name;
NSString *subLocality=placemark.subLocality;
NSString *postalCode=placemark.postalCode;
NSMutableArray *listData;
if (!listData) listData = [[NSMutableArray alloc] init];
[listData addObject:LocationDetails];
NSLog(@"the Location details %@", listData);
NSString *location=[NSString stringWithFormat:@"You are now in %@ inside the sublocality of %@ and pin code is %@",name,subLocality,postalCode];
UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"Location Update" message:location delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[Alert show];
}
];
// }
// contains the code you posted to start the timer
}
- (IBAction)getLocation:(id)sender {
[ self startTimer];
}
答案 0 :(得分:1)
在初始化类时,不要使用getLocation
方法,而是执行所有CLLocationManager
初始化。在@interface
设置属性以保存用户的当前位置:
@property (nonatomic, strong) CLLocation *currentLocation;
并像这样实现委托方法-locationManager:didUpdateLocations:
:
- (void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray*)locations
{
// set the current location. The most recent location is always at the end of the
// if there are multiple locations
_currentLocation = locations[locations.count - 1];
}
然后,取代CLLocationCoordinate2D coordinate = [self getLocation];
,获取位置:
CLLocationCoordinate2D coordinate = _currentLocation.coordinate; // I think that's the right property.
注意:确保您的课程符合CLLocationManagerDelegate