【问题标题】:iOS update location even when app is terminated即使应用程序终止,iOS也会更新位置
【发布时间】:2015-05-01 13:40:19
【问题描述】:

即使应用程序终止,我也会尝试更新用户位置。我向我的 .plist 添加了地图和后台模式 --> 位置更新,并设置了一个本地通知,该通知将在位置更新时触发。但它从未被解雇。我在 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];
    }

我在以高速公路驱动器为位置的模拟器上测试了此代码,但它不起作用。


编辑

如果我将代码放在applicationDidEnterBackground 下,授权请求将在它打开的第二秒关闭,因为我使用的是didFinishLaunchingWithOptions。我知道它是 24 小时跟踪位置,因为即使应用程序终止,也有 GPS 符号。


编辑 2

在我的手机上测试后,代码可以工作。它唤醒终止的应用程序并发送本地通知。它不适用于模拟器,但适用于现实生活(设备):)

【问题讨论】:

  • 你在高速公路上等了多久?根据 Apple 的说法:“应用程序可以在设备从之前的通知移动 500 米或更远时收到通知。它的通知频率不应超过每五分钟一次。如果设备能够从网络中检索数据,位置经理更有可能及时发送通知。” developer.apple.com/library/ios/documentation/CoreLocation/…
  • 从开始到结束,我没有收到任何通知。
  • 等等,为什么你在 didFinishLaunchingWithOptions 下编码?不应该在 applicationDidEnterBackground 下吗?

标签: ios background cllocationmanager


【解决方案1】:

看起来您正在使用 CLLocationManagerDelegate 的已弃用函数:

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

相反,您应该实施

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

【讨论】:

  • 以上代码仅适用于非挂起状态的前台和后台。
  • 实际上 @iThink 作为 OP 称为 [locationManager startMonitoringSignificantLocationChanges] 我希望这个委托也会在发生重大位置变化时在后台被调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
  • 2017-07-30
  • 1970-01-01
  • 2016-04-15
  • 2022-01-19
  • 2016-04-07
相关资源
最近更新 更多