在初始加載時找不到當前位置,或在多任務後恢復當前位置。這是我有:核心位置未找到當前位置
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