首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CLLocation调用委托方法

CLLocation调用委托方法
EN

Stack Overflow用户
提问于 2015-04-21 00:38:15
回答 1查看 256关注 0票数 1

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

FeedVC.h

代码语言:javascript
复制
#import <CoreLocation/CoreLocation.h>
@interface FeedVC : UIViewController <CLLocationManagerDelegate>

FeedVC.m

代码语言:javascript
复制
@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没有显示),我在这里跟踪了所有的文档和其他答案,但是我找不到问题的根源,谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-21 01:08:51

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

代码语言:javascript
复制
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [locationManager startUpdatingLocation];
    }
}

如果您还没有在plist中添加NSLocationWhenInUseUsageDescription,那么添加它来描述为什么要使用位置服务。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29760869

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档