我的 Apple Watch 应用程序需要一些数据,并从相应的 iPhone 应用程序请求这些数据。为了满足请求,iPhone 应用程序需要用户位置。在收到并使用真正的 Apple Watch 进行测试后,我发现我的 iPhone 应用程序在后台运行时没有接收到位置更新。如果 iPhone 应用程序在前台处于活动状态,则它可以正常工作。使用模拟器,它在这两种情况下都有效。
在这两种情况下(活动和后台),WatchKit 扩展程序调用并成功启动 iPhone 应用程序并一直运行,直到在 iPhone 应用程序中调用 startUpdatingLocation。但是如果应用程序在后台运行,didUpdateLocations 永远不会被调用。
我尝试了 requestAlwaysAuthorization 和 requestWhenInUseAuthorization。没有不同。然后我还激活了功能内的“位置更新”后台模式。但又没有区别。
是否有其他人面临同样的问题并找到了一种在后台也接收位置的方法?
这里有一些代码。首先检查是否需要授权。
// iOS 8 check to avoid crash on older iOS
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
{
[self requestLocationAlwaysAuthorization];
}
else
{
[self runLocationUpdate];
}
在这里检查正确的位置管理员权限。
- (void)requestLocationAlwaysAuthorization
{
CLAuthorizationStatus currentAuthStatus = [CLLocationManager authorizationStatus];
if (currentAuthStatus == kCLAuthorizationStatusDenied)
{
//request user to change setting
}
else if (currentAuthStatus == kCLAuthorizationStatusRestricted)
{
//request user to change setting
}
else if (currentAuthStatus == kCLAuthorizationStatusNotDetermined)
{
[self.locationManager requestAlwaysAuthorization];
[self runLocationUpdate];
}
else if (currentAuthStatus == kCLAuthorizationStatusAuthorizedWhenInUse)
{
//maybe when in use is also enough?
[self runLocationUpdate];
}
else if (currentAuthStatus == kCLAuthorizationStatusAuthorizedAlways)
{
//all ok
[self runLocationUpdate];
}
}
这里调用 startUpdatingLocation。只有在 iPhone 应用程序处于活动状态时才会调用 didUpdateLocations 委托。
-(void)runLocationUpdate
{
[self.locationManager startUpdatingLocation];
}