How do I get a background location update every n minutes in my iOS application?

后端 未结 14 1152
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 02:00

I\'m looking for a way to get a background location update every n minutes in my iOS application. I\'m using iOS 4.3 and the solution should work for non-jailbroken iPhones

相关标签:
14条回答
  • 2020-11-22 02:11

    I used xs2bush's method of getting an interval (using timeIntervalSinceDate) and expanded on it a little bit. I wanted to make sure that I was getting the required accuracy that I needed and also that I was not running down the battery by keeping the gps radio on more than necessary.

    I keep location running continuously with the following settings:

    locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
    locationManager.distanceFilter = 5;
    

    this is a relatively low drain on the battery. When I'm ready to get my next periodic location reading, I first check to see if the location is within my desired accuracy, if it is, I then use the location. If it's not, then I increase the accuracy with this:

    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    locationManager.distanceFilter = 0;
    

    get my location and then once I have the location I turn the accuracy back down again to minimize the drain on the battery. I have written a full working sample of this and also I have written the source for the server side code to collect the location data, store it to a database and allow users to view gps data in real time or retrieve and view previously stored routes. I have clients for iOS, android, windows phone and java me. All clients are natively written and they all work properly in the background. The project is MIT licensed.

    The iOS project is targeted for iOS 6 using a base SDK of iOS 7. You can get the code here.

    Please file an issue on github if you see any problems with it. Thanks.

    0 讨论(0)
  • 2020-11-22 02:13

    On iOS 8/9/10 to make background location update every 5 minutes do the following:

    1. Go to Project -> Capabilities -> Background Modes -> select Location updates

    2. Go to Project -> Info -> add a key NSLocationAlwaysUsageDescription with empty value (or optionally any text)

    3. To make location working when your app is in the background and send coordinates to web service or do anything with them every 5 minutes implement it like in the code below.

    I'm not using any background tasks or timers. I've tested this code with my device with iOS 8.1 which was lying on my desk for few hours with my app running in the background. Device was locked and the code was running properly all the time.

    @interface LocationManager () <CLLocationManagerDelegate>
    @property (strong, nonatomic) CLLocationManager *locationManager;
    @property (strong, nonatomic) NSDate *lastTimestamp;
    
    @end
    
    @implementation LocationManager
    
    + (instancetype)sharedInstance
    {
        static id sharedInstance = nil;
    
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            sharedInstance = [[self alloc] init];
            LocationManager *instance = sharedInstance;
            instance.locationManager = [CLLocationManager new];
            instance.locationManager.delegate = instance;
            instance.locationManager.desiredAccuracy = kCLLocationAccuracyBest; // you can use kCLLocationAccuracyHundredMeters to get better battery life
            instance.locationManager.pausesLocationUpdatesAutomatically = NO; // this is important
        });
    
        return sharedInstance;
    }
    
    - (void)startUpdatingLocation
    {
        CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    
        if (status == kCLAuthorizationStatusDenied)
        {
            NSLog(@"Location services are disabled in settings.");
        }
        else
        {
            // for iOS 8
            if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
            {
                [self.locationManager requestAlwaysAuthorization];
            }
            // for iOS 9
            if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)])
            {
                [self.locationManager setAllowsBackgroundLocationUpdates:YES];
            }
    
            [self.locationManager startUpdatingLocation];
        }
    }
    
    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
    {
        CLLocation *mostRecentLocation = locations.lastObject;
        NSLog(@"Current location: %@ %@", @(mostRecentLocation.coordinate.latitude), @(mostRecentLocation.coordinate.longitude));
    
        NSDate *now = [NSDate date];
        NSTimeInterval interval = self.lastTimestamp ? [now timeIntervalSinceDate:self.lastTimestamp] : 0;
    
        if (!self.lastTimestamp || interval >= 5 * 60)
        {
            self.lastTimestamp = now;
            NSLog(@"Sending current location to web service.");
        }
    }
    
    @end
    
    0 讨论(0)
  • 2020-11-22 02:13

    I did this in an application I'm developing. The timers don't work when the app is in the background but the app is constantly receiving the location updates. I read somewhere in the documentation (i can't seem to find it now, i'll post an update when i do) that a method can be called only on an active run loop when the app is in the background. The app delegate has an active run loop even in the bg so you dont need to create your own to make this work. [Im not sure if this is the correct explanation but thats how I understood from what i read]

    First of all, add the location object for the key UIBackgroundModes in your app's info.plist. Now, what you need to do is start the location updates anywhere in your app:

        CLLocationManager locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self;//or whatever class you have for managing location
        [locationManager startUpdatingLocation];
    

    Next, write a method to handle the location updates, say -(void)didUpdateToLocation:(CLLocation*)location, in the app delegate. Then implement the method locationManager:didUpdateLocation:fromLocation of CLLocationManagerDelegate in the class in which you started the location manager (since we set the location manager delegate to 'self'). Inside this method you need to check if the time interval after which you have to handle the location updates has elapsed. You can do this by saving the current time every time. If that time has elapsed, call the method UpdateLocation from your app delegate:

    NSDate *newLocationTimestamp = newLocation.timestamp;
    NSDate *lastLocationUpdateTiemstamp;
    
    int locationUpdateInterval = 300;//5 mins
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if (userDefaults) {
    
            lastLocationUpdateTiemstamp = [userDefaults objectForKey:kLastLocationUpdateTimestamp];
    
            if (!([newLocationTimestamp timeIntervalSinceDate:lastLocationUpdateTiemstamp] < locationUpdateInterval)) {
                //NSLog(@"New Location: %@", newLocation);
                [(AppDelegate*)[UIApplication sharedApplication].delegate didUpdateToLocation:newLocation];
                [userDefaults setObject:newLocationTimestamp forKey:kLastLocationUpdateTimestamp];
            }
        }
    }
    

    This will call your method every 5 mins even when your app is in background. Imp: This implementation drains the battery, if your location data's accuracy is not critical you should use [locationManager startMonitoringSignificantLocationChanges]

    Before adding this to your app, please read the Location Awareness Programming Guide

    0 讨论(0)
  • 2020-11-22 02:20

    I did write an app using Location services, app must send location every 10s. And it worked very well.

    Just use the "allowDeferredLocationUpdatesUntilTraveled:timeout" method, following Apple's doc.

    What I did are:

    Required: Register background mode for update Location.

    1. Create LocationManger and startUpdatingLocation, with accuracy and filteredDistance as whatever you want:

    -(void) initLocationManager    
    {
        // Create the manager object
        self.locationManager = [[[CLLocationManager alloc] init] autorelease];
        _locationManager.delegate = self;
        // This is the most important property to set for the manager. It ultimately determines how the manager will
        // attempt to acquire location and thus, the amount of power that will be consumed.
        _locationManager.desiredAccuracy = 45;
        _locationManager.distanceFilter = 100;
        // Once configured, the location manager must be "started".
        [_locationManager startUpdatingLocation];
    }
    

    2. To keep app run forever using allowDeferredLocationUpdatesUntilTraveled:timeout method in background, you must restart updatingLocation with new parameter when app moves to background, like this:

    - (void)applicationWillResignActive:(UIApplication *)application {
         _isBackgroundMode = YES;
    
        [_locationManager stopUpdatingLocation];
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        [_locationManager setDistanceFilter:kCLDistanceFilterNone];
        _locationManager.pausesLocationUpdatesAutomatically = NO;
        _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        [_locationManager startUpdatingLocation];
     }
    

    3. App gets updatedLocations as normal with locationManager:didUpdateLocations: callback:

    -(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
    {
    //  store data
        CLLocation *newLocation = [locations lastObject];
        self.userLocation = newLocation;
    
       //tell the centralManager that you want to deferred this updatedLocation
        if (_isBackgroundMode && !_deferringUpdates)
        {
            _deferringUpdates = YES;
            [self.locationManager allowDeferredLocationUpdatesUntilTraveled:CLLocationDistanceMax timeout:10];
        }
    }
    

    4. But you should handle the data in then locationManager:didFinishDeferredUpdatesWithError: callback for your purpose

    - (void) locationManager:(CLLocationManager *)manager didFinishDeferredUpdatesWithError:(NSError *)error {
    
         _deferringUpdates = NO;
    
         //do something 
    }
    

    5. NOTE: I think we should reset parameters of LocationManager each time app switches between background/forground mode.

    0 讨论(0)
  • 2020-11-22 02:23

    It seems that stopUpdatingLocation is what triggers the background watchdog timer, so I replaced it in didUpdateLocation with:

         [self.locationManager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];
         [self.locationManager setDistanceFilter:99999];
    

    which appears to effectively power down the GPS. The selector for the background NSTimer then becomes:

    - (void) changeAccuracy {
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [self.locationManager setDistanceFilter:kCLDistanceFilterNone];
    }
    

    All I'm doing is periodically toggling the accuracy to get a high-accuracy coordinate every few minutes and because the locationManager hasn't been stopped, backgroundTimeRemaining stays at its maximum value. This reduced battery consumption from ~10% per hour (with constant kCLLocationAccuracyBest in the background) to ~2% per hour on my device

    0 讨论(0)
  • 2020-11-22 02:24

    Unfortunately, all of your assumptions seem correct, and I don't think there's a way to do this. In order to save battery life, the iPhone's location services are based on movement. If the phone sits in one spot, it's invisible to location services.

    The CLLocationManager will only call locationManager:didUpdateToLocation:fromLocation: when the phone receives a location update, which only happens if one of the three location services (cell tower, gps, wifi) perceives a change.

    A few other things that might help inform further solutions:

    • Starting & Stopping the services causes the didUpdateToLocation delegate method to be called, but the newLocation might have an old timestamp.

    • Region Monitoring might help

    • When running in the background, be aware that it may be difficult to get "full" LocationServices support approved by Apple. From what I've seen, they've specifically designed startMonitoringSignificantLocationChanges as a low power alternative for apps that need background location support, and strongly encourage developers to use this unless the app absolutely needs it.

    Good Luck!

    UPDATE: These thoughts may be out of date by now. Looks as though people are having success with @wjans answer, above.

    0 讨论(0)
提交回复
热议问题