【问题标题】:iOS: Watch Kit get current location and show on mapiOS:Watch Kit 获取当前位置并显示在地图上
【发布时间】:2016-01-23 02:17:00
【问题描述】:

我有一个 iOS 应用程序,它使用用户当前位置来显示用户当前位置和目的地点之间的方向/距离。我能够在地图上显示目的地点,但是当我尝试使用 CLlocationManager 获取用户的当前位置时,它返回坐标 (0,0)。下面是我检索用户位置的代码。

是否可以在 Apple Watch 上检索当前位置?

如果是这样,我在这里做错了什么,位置正在返回 (0,0)?

CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
locationManager.distanceFilter = 5;
CLLocation *location = locationManager.location;

CLLocationCoordinate2D myLoc = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);

另外,我的 .h 文件中有 #import

【问题讨论】:

  • 你是否像 NSLocationAlwaysUsageDescription 一样向你的 plsit 添加了所需的键?
  • :( 不,我绝对忘了这样做...
  • @Mr.T 我已将 NSLocationAlwaysUsageDescription 添加到 plist 中,并且 Maps 在 Capabilities 选项卡下已打开,您知道 locationManager 不返回位置的其他原因吗?
  • 你使用 watchOS 1 还是 2?

标签: ios objective-c watchkit


【解决方案1】:

如果你没有实现这个: (使用属性检查器或以编程方式)

self.mapView.showsUserLocation = YES

或者除了告诉mapView用户的位置取决于LocationManager.location

【讨论】:

  • 这是在 Apple Watch 上,WKInterfaceMap 上没有一个名为 showsUserLocation 的属性,你知道其他解决方案吗?
  • 抱歉,我没有仔细阅读,我对 Watch Kit 框架了解不多……但是,返回 LocationManager.location 是什么?
  • LocationManager.location 返回 null
  • 在 Watch Kit 框架中,Core Location 有委托方法吗?喜欢 didUpdateUserLocation 吗?
  • 不,所有的位置委托方法都是通过手机设备完成的,但是Watch Kit有自己的地图对象。在处理地图时,您无法在手表中做几件事,但我想我至少应该能够获得当前位置。
【解决方案2】:

试试下面的代码:

@property (nonatomic, strong) CLLocationManager *locationManager;

- (void)willActivate
{
    self.locationManager = [[CLLocationManager alloc] init];
    [self.locationManager setDelegate:self];
    [self.locationManager requestLocation];
}

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations
{
    if ([locations count] == 0) {
        // error
        return;
    }

    // success
    self.currentLocation = [locations firstObject];
    CLLocationCoordinate2D myLoc = CLLocationCoordinate2DMake(
        self.currentLocation.coordinate.latitude, 
        self.currentLocation.coordinate.longitude);
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(nonnull NSError *)error
{
    // error
}

【讨论】:

  • 完美运行,谢谢!对于寻找此答案的其他人,省略 didFailWithError 方法会导致崩溃,请确保将密钥添加到手表扩展目标上的 info.plist,并在手表扩展目标的功能选项卡下启用地图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-09
  • 1970-01-01
  • 1970-01-01
  • 2013-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多