简体   繁体   中英

Fetch current location on each launch of app ios

I am developing iOS app, i want to load current location of user on every launch of app.

I have written this code snippet in didFinishLaunchingWithOptions but it fetches users location only once first time when i launch my app. (i am testing my app in 5s iOS 7)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    locationManager = [[CLLocationManager alloc] init];

                locationManager.delegate = self;
                if(IS_OS_8_OR_LATER){
                    NSUInteger code = [CLLocationManager authorizationStatus];
                    if (code == kCLAuthorizationStatusNotDetermined && ([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)] || [locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) {
                        // choose one request according to your business.
                        if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]){
                            [locationManager requestAlwaysAuthorization];
                        } else if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) {
                            [locationManager  requestWhenInUseAuthorization];
                        } else {
                            NSLog(@"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription");
                        }
                    }
                }
                [locationManager startUpdatingLocation];


                 ...
                 ...
                 ...
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{

    CLLocation *currentLocation = newLocation;
    [locationManager stopUpdatingLocation];
}

now when i go my home the location is changed, and when i try to open my app it doesn't fetch home location instead it shows my old location only.(There is much difference between my old location and home location)

Please help, and thanks in advance.

I think you're looking for applicationWillEnterForeground or applicationDidBecomeActive , which are called every time the user opens your application ('becomes active').

didFinishLaunchingWithOptions is only called once, on the initial launch of your application.

From the docs , an overview of the state transition events:

Launch time:

application:willFinishLaunchingWithOptions

application:didFinishLaunchingWithOptions

Transitioning to the foreground:

applicationDidBecomeActive

Transitioning to the background:

applicationDidEnterBackground

Transitioning to the inactive state

applicationWillResignActive (Called when leaving the foreground state.)

applicationWillEnterForeground (Called when transitioning out of the background state.)

Termination:

applicationWillTerminate (Called only when the app is running. This method is not called if the app is suspended.)

Write your code in applicationDidBecomeActive . It is called everytime you come from background.

- (void)applicationDidBecomeActive:(UIApplication *)application {
//Get Current Location
    if ([CLLocationManager locationServicesEnabled])
    {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.pausesLocationUpdatesAutomatically = NO;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        // Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
        if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [self.locationManager requestAlwaysAuthorization];
        }
        [self.locationManager startUpdatingLocation];
    }
    else
    {
        NSLog(@"Location services are not enabled");
    }
}

#pragma mark -- Location Delegate Methods

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = [locations lastObject];
    if (location != nil)    
        NSLog(@"current lat:%f , currentLong:%f",location.coordinate.latitude,location.coordinate.longitude);

    [manager stopUpdatingLocation];
}

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

-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
        case kCLAuthorizationStatusRestricted:
        case kCLAuthorizationStatusDenied:
        {
            // do some error handling
        }
            break;
        default:{
            [self.locationManager startUpdatingLocation];
        }
            break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM