7

如何在 Watch Kit 扩展中计算当前用户位置,因为我们不能CoreLocation在 watch kit 中使用。

提前致谢

4

3 回答 3

10

您可以在手表应用程序扩展中使用 CoreLocation,与在 iPhone 应用程序中使用它的方式非常相似。主要区别在于用户无法授权您的扩展程序访问核心位置。他们将需要从您的 iPhone 应用程序中执行此操作。因此,您需要检查用户是否为您的应用授权了定位服务,如果没有,您需要指导他们如何操作。

这是我在手表套件扩展中使用的代码,用于跟踪当前位置。(GPWatchAlertView是我为显示警报消息而制作的自定义控制器。)

#pragma mark - CLLocation Manager 

-(void)startTrackingCurrentLocation:(BOOL)forTrip
{
    if (self.locationManager == nil)
    {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        self.locationManager.activityType = CLActivityTypeFitness;
        self.locationManager.distanceFilter = 5; //Require 15 meters of movement before we show an update
    }

    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse)
    {
        NSLog(@"%@ Start tracking current location", self);

        self.trackingCurrentLocation = YES;
        self.gpsTrackingForTrip = forTrip;

        //We wait until we have a GPS point before we start showing it
        self.showCurrentLocation = NO;
        [self.locationManager startUpdatingLocation];
    }
    else
    {
        [self presentControllerWithName:@"GPWatchAlertView" context:@"Unauthorized GPS Access.  Please open Topo Maps+ on your iPhone and tap on current location."];
    }

}

-(void)stopTrackingCurrentLocation:(id)sender
{
    NSLog(@"%@ Stop tracking current location", self);

    self.trackingCurrentLocation = NO;
    [self.locationManager stopUpdatingLocation];
    self.showCurrentLocation = NO;
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation* loc = [locations lastObject];

   ... 

}
于 2015-01-15T13:15:02.783 回答
3

Stephan 的答案应该有效(尚未测试),只有一个例外。WatchKit 需要位置管理的“始终”权限。这是因为您的手机确实在后台模式下运行手表扩展程序。因此,如果您只要求“使用时”权限,您将永远不会将位置返回到您的手表扩展程序。

尝试换行:

if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse)

和:

if (status == kCLAuthorizationStatusAuthorizedAlways)
于 2015-04-16T17:26:07.287 回答
1

您应该在 iphone 应用程序上获取用户位置,而不是在扩展程序中。请查看苹果文档

于 2015-04-17T11:50:06.917 回答