我试图在切换到特定的视图控制器(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没有显示),我在这里跟踪了所有的文档和其他答案,但是我找不到问题的根源,谢谢!
发布于 2015-04-21 01:08:51
不要在[locationManager startUpdatingLocation];中调用viewDidLoad,在委托方法中调用它:
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
[locationManager startUpdatingLocation];
}
}如果您还没有在plist中添加NSLocationWhenInUseUsageDescription,那么添加它来描述为什么要使用位置服务。
https://stackoverflow.com/questions/29760869
复制相似问题