iOS App Background Location (Push Notifications)

心已入冬 提交于 2019-12-04 18:19:28

As discussed I used alternative solution, here it is:

Under viewDidLoad or didFinishingLaunchingWithOptions add:

locationsLogged = [[NSMutableArray alloc] init];
lastLocationTime = [[NSDate alloc] init]
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];

Under applicationDidEnterBackground add:

[locationManager startMonitoringSignificantLocationChanges];

Add:

-(void) storeLocations:(CLLocation *)location
{
bgTask = [[UIApplication sharedApplication]
          beginBackgroundTaskWithExpirationHandler:
          ^{
              [[UIApplication sharedApplication] endBackgroundTask:bgTask];
               }];

[locationsLogged addObject:location];

if (bgTask != UIBackgroundTaskInvalid)
{
    [[UIApplication sharedApplication] endBackgroundTask:bgTask];
     bgTask = UIBackgroundTaskInvalid;
     }
}


 -(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
    isInBackground = YES;
} 


NSDate *now = [NSDate date];
NSTimeInterval diff = [now timeIntervalSinceDate:lastLocationTime];


if ((int)diff > 600) {

    if (isInBackground)
    {
        [lastLocationTime release];
        lastLocationTime = [[NSDate alloc] init];
        [self storeLocations:newLocation];
    }
    else
    {
        // ...
    }
}
}

Then on applicationDidBecomeActive you can use whatever logic you need to apply location information.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!