CLLocation调用委托方法

时间:2015-04-21 00:38:16

标签: ios objective-c core-location

我试图在切换到特定视图控制器(FeedVC)时获取用户位置,这是我目前拥有的代码:

FeedVC.h

#import <CoreLocation/CoreLocation.h>
@interface FeedVC : UIViewController <CLLocationManagerDelegate>

FeedVC.m

@implementation FeedVC
{
    CLLocationManager *locationManager;
    CLLocation *location;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    if (!locationManager)
        locationManager = [[CLLocationManager alloc] init];

    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
        [locationManager requestWhenInUseAuthorization];

    [locationManager startUpdatingLocation];
}

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    NSLog(@"did update locations");

    location = [locations lastObject];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
}

-(void) viewWillAppear:(BOOL)animated
{
    NSLog(@"%.2f", location.coordinate.latitude);
}

方法locationManager: didUpdateLocations:未被调用(因为NSLog没有显示)我已经按照所有文档和其他答案进行了操作但是我找不到问题的根源,谢谢!

1 个答案:

答案 0 :(得分:0)

请勿在viewDidLoad中调用[locationManager startUpdatingLocation];, 在委托方法中调用它:

-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [locationManager startUpdatingLocation];
    }
}

如果您没有在plist中添加NSLocationWhenInUseUsageDescription,请添加它以描述您要使用位置服务的原因