无法获取我的位置进行更新

时间:2013-11-21 04:52:35

标签: ios objective-c cllocationmanager

ViewController启动LocationTracking。我想NSLog的位置更新(当模拟器在高速公路上时),但didUpdateLocations仅在我取消注释NSTimer时才会记录,我无法弄清楚原因。我觉得这真的很愚蠢,这可能很简单,我对此很陌生,并且花了很长时间试图解决这个问题。

ViewController:

#import "ViewController.h"

@interface ViewController ()


@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults boolForKey:@"locationUpdate"]) {
        LocationTracking *locationTracker = [[LocationTracking alloc] init];
        [locationTracker startTracking];
        NSLog(@"location tracking did");
        //NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 target:locationTracker selector:@selector(logLast) userInfo:nil repeats:YES];

    }

}

LocationTracking.h:

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

@interface LocationTracking : NSObject <CLLocationManagerDelegate>
@property (nonatomic, strong) NSMutableArray *locations;
-(void) startTracking;
-(void) logLast;

@end

LocationTracking.m:

#import "LocationTracking.h"

@interface LocationTracking()
@property (nonatomic, strong) CLLocationManager *locationManager;

@end

@implementation LocationTracking

-(void)startTracking
{
    self.locations = [[NSMutableArray alloc] init];
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    [self.locationManager setDelegate:self];
    [self.locationManager startUpdatingLocation];

}

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

-(void)logLast
{

}

1 个答案:

答案 0 :(得分:0)

以下代码适用于我:

#import "ViewController.h"
@import CoreLocation;

@interface ViewController () <CLLocationManagerDelegate>

@property (strong,nonatomic) CLLocationManager *locationManager;

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    [self.locationManager setDelegate:self];
    [self.locationManager startUpdatingLocation];

}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

    CLLocation *loc = [locations lastObject];
    NSString *lat = [NSString stringWithFormat:@"%.2f",loc.coordinate.latitude];
    NSString *lon = [NSString stringWithFormat:@"%.2f",loc.coordinate.longitude];

    NSLog(@"location is: %@, %@",lat,lon);
}


@end

如果您在Xcode中使用模拟器,请不要忘记设置模拟器的位置。新项目默认为“无”。