如何计算WatchKit扩展中的当前位置

Moh*_*ani 7 ios apple-watch watchkit

如何计算Watch Kit扩展中的当前用户位置,因为我们无法CoreLocation在手表套件中使用.

提前致谢

Ste*_*son 10

您可以在手表应用扩展程序中使用CoreLocation,与在iPhone应用中使用它的方式非常相似.关键区别在于用户无法授权您的扩展程序可以访问Core Location.他们需要从你的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];

   ... 

}
Run Code Online (Sandbox Code Playgroud)