即使应用终止,iOS更新位置 [英] iOS update location even when app is terminated
问题描述
即使应用终止,我仍在尝试更新用户位置.我在.plist中添加了地图和背景模式->位置更新,并设置了一个在位置更新时将触发的本地通知.但它从未被解雇.我在 AppDelegat.h 中拥有这个:
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;
}
和 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];
}
我在模拟器上以Freeway驱动器作为位置测试了此代码,但它不起作用.
I tested this code on simulator with Freeway drive as location and it doesn't work.
编辑
如果我将代码放在applicationDidEnterBackground
下,授权请求将在打开它的第二秒关闭,因为我使用的是didFinishLaunchingWithOptions
.我知道它的追踪位置是24小时,因为即使应用终止,也会有GPS符号.
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.
编辑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) :)
推荐答案
您似乎正在使用CLLocationManagerDelegate的不赞成使用的功能:
It looks like you're using CLLocationManagerDelegate's deprecated function:
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
}
相反,您应该实现
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
}
这篇关于即使应用终止,iOS更新位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!