在初始加载时找不到当前位置,或在多任务后恢复当前位置。这是我有:核心位置未找到当前位置
ViewController.h
@interface ViewController : UIViewController <CLLocationManagerDelegate, ADBannerViewDelegate, BEMSimpleLineGraphDelegate>
ViewController.m
@interface ViewController(){
CLLocationManager *locationManager;
CLLocation *location;
CLLocationCoordinate2D coordinate;
int timeofday;
NSString *cityName;
NSMutableArray *ArrayOfValues;
}
@end
再往下:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLabels) name:UIApplicationWillEnterForegroundNotification object:nil];
// set up coordinates for current location
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = (id)self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
location = [locationManager location];
}
然后我的更新标签的方法(其中有其他代码在下面更新我的观点):
- (void)updateLabels
{
CLLocationCoordinate2D currentLocation = [location coordinate];
if (currentLocation.latitude) {
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:location
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error){
NSLog(@"Geocode failed with error: %@", error);
return;
}
CLPlacemark *placemark = [placemarks objectAtIndex:0];
cityName = [NSString stringWithFormat:@"%@ is currently",placemark.locality];
}];
[self updateLabels];
} else {
NSLog(@"Could not find the location.");
}
}
这里是cclocationmanager 2委托方法:
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError: %@", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
//NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
[self updateLabels];
[locationManager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error){
NSLog(@"Geocode failed with error: %@", error);
return;
}
// CLPlacemark *placemark = [placemarks objectAtIndex:0];
}];
}
您是否尝试将'[locationManager startUpdatingLocation];'从'viewDidLoad'移动到'viewWillAppear'或'viewDidAppear'? – Stonz2
您的应用程序是否具有渗透使用您的位置?在“设置”应用中查看位置隐私设置.. –
是的,它可以在我的测试设备上以及在模拟器中(在打开应用程序之前选择了自定义位置,并在运行应用程序时验证位置仍然处于选中状态)。 – TerryG