Search code examples
iphonecocoa-touchcllocationmanageruserlocation

iPhone - Initial user location with CCLocationManager


I'm using that code running on an iPhone 4 :

- (id)init
{
    self = [super initWithNibName:@"OfflineView" bundle:nil]; // ok, not perfect but for test, that works fine
    if (self) {
        self.locationMgr = [[CLLocationManager alloc] init];
        self.locationMgr.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
        self.locationMgr.distanceFilter = kCLDistanceFilterNone;
        self.locationMgr.headingFilter = kCLHeadingFilterNone;

        self.locationMgr.delegate = self;
    }
    return self;
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    // do things
}

// triggered when showing the view, first call here after the init
- (void) start
{
    self.view.hidden = NO;
    [self.locationMgr startUpdatingLocation];
    [self.locationMgr startUpdatingHeading];
}

but the delegate method is not triggered.
It's only triggered when the phone moves.

How may I init my process with a valid user location when the view appears, without asking my user to shake it phone and make a 100m run, before being able to do something ?


Solution

  • You could "prime" it by kicking the delegate method yourself once.

    - (void) start
    {
        self.view.hidden = NO;
        [self.locationMgr startUpdatingLocation];
        [self.locationMgr startUpdatingHeading];
        [self locationManager: self.locationMgr didUpdateToLocation: [self.locationMgr currentLocation] fromLocation: nil];
    }