-->

CLLocationManager not working all the time (iOS 8,

2019-03-27 06:15发布

问题:

Basically half the time the delegate method

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

is not called at all. But the other half of the time it works perfectly! I've found that it usually happens when I first start up Xcode after closing and quitting it, but then after that or a couple runs after that it seems to work fine. I'm not 100% sure if it's just an Xcode problem or what, I'll be getting a developer's license soon so I'll see if it will work fine on an actual device.

Starting from the viewDidAppear (tried in viewDidLoad also, made no difference), I run a method to init my locationManager stuff:

locationManager = [[CLLocationManager alloc]init];

[locationManager setDelegate:self];
locationManager.distanceFilter = 20.0f;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.pausesLocationUpdatesAutomatically = NO;

if ([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
    [locationManager requestAlwaysAuthorization];

[locationManager startUpdatingLocation];

Sometimes this works, sometimes it doesn't. I even made a timer to re-run this every so-and-so seconds, and this doesn't work.

Is there something else I should do? Is there any answer to this problem?

Thanks.

回答1:

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

This delegate method is invoked only if new locations are available. Sometimes gps will not get satellite signal hence locations cannot be obtained. So in these situations the above mentioned method will not get triggered. Since you are testing in simulator,you should change or set the location. I think it will work fine on an actual device.



回答2:

add in viewdidappear

_locamangr = [CLLocationManager new];
    _locamangr.delegate = self;
    //    _locamangr.distanceFilter = kCLDistanceFilterNone;
    _locamangr.desiredAccuracy = kCLLocationAccuracyBest;
    if ([_locamangr respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        [_locamangr requestAlwaysAuthorization] ;
        [_locamangr requestWhenInUseAuthorization];
    }
    [_locamangr startUpdatingLocation];

and set in infoplist. NSLocationWhenInUseUsageDescription NSLocationAlwaysUsageDescription