Xcode 5 didupdatelocations无法正常工作

问题描述:

我正在学习本教程以创建一个显示用户位置的程序。我已经告诉Xcode为我模拟了一个位置,甚至在模拟器上也确保它允许我的应用程序跟踪位置。但是,没有任何记录到我的控制台。Xcode 5 didupdatelocations无法正常工作

头文件:

#import <UIKit/UIKit.h> 
#import <CoreLocation/CoreLocation.h> 

@interface WhereamiViewController : UIViewController <CLLocationManagerDelegate> { 
    CLLocationManager *locationManager; 
} 

@end 

和主文件:

#import "WhereamiViewController.h" 

@implementation WhereamiViewController 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 

    if (self) { 
     locationManager = [[CLLocationManager alloc] init]; 
     [locationManager setDelegate:self]; 
     [locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; 
     [locationManager setPausesLocationUpdatesAutomatically:NO]; 
     [locationManager startUpdatingLocation]; 
    } 

    return self; 
} 

- (void)locationManager:(CLLocationManager *)manager 
    didUpdateLocations:(NSArray *)locations 
{ 
    NSLog(@"%@", [locations lastObject]); 
} 

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

@end 
+0

[CLLocationManager不会将位置发送到didUpdateLocations方法](http://stackoverflow.com/questions/15656889/cllocationmanager-does-not-send-location-to-the-didupdatelocations-method) –

+0

@ josh它工作,如果我把我的代码到viewDidLoad,但不是当它在initWithNibName。这是为什么?最初initWithNibName甚至没有被调用,所以我把它设置在我的AppDelegate.m中'WhereamiViewController * wvc = [[WhereamiViewController alloc] initWithNibName:@“WhereamiViewController”bundle:nil];' – Thomas

我不是100%肯定的答案,但是这是我有。
仅当应用处于前景时,iOS 7才允许进行位置获取。 当您在initwithNibName中编写代码时,您的应用程序实际上并不处于前台,它正在从xib文件和全部文件创建控件。这就是操作系统未给您位置更新的原因。

+0

这对我来说是这样。我在'application didFinishLaunchingWithOptions'的第一次测试期间调用了'startUpdatingLocation',这似乎为时尚早。从一个按钮调用它之后,一切按预期工作。 –