iOS update location even when app is terminated

只谈情不闲聊 提交于 2019-12-02 03:24:11

问题


I'm trying to update users location even when app is terminated. I added maps, and background mode --> Location update to my .plist, and I set an local notification that will fire when location is updated. But it never got fired. I have this in AppDelegat.h:

@interface AppDelegate : UIResponder <CLLocationManagerDelegate>{
    CLLocationManager *locationManager;
}

and in AppDelegate.m

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

    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager requestAlwaysAuthorization];
    [locationManager startMonitoringSignificantLocationChanges];
}

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

 UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.repeatInterval = NSDayCalendarUnit;
[notification setAlertBody:@"Location update!"];
[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[notification setTimeZone:[NSTimeZone  defaultTimeZone]];
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }

I tested this code on simulator with Freeway drive as location and it doesn't work.


EDIT

If I put the code under applicationDidEnterBackground authorization request will close the second it's opened, because I'm using didFinishLaunchingWithOptions. I know it's tracking location 24h because there's GPS symbol even when app is terminated.


EDIT 2

After testing it on my phone the code works. It wakes terminated app and sends local notification. It doesn't work on simulator but works in real life(device) :)


回答1:


It looks like you're using CLLocationManagerDelegate's deprecated function:

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

Instead you should implement

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


来源:https://stackoverflow.com/questions/28788865/ios-update-location-even-when-app-is-terminated

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