You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用iOS MapKit的MKDirections.Request报错的原因及解决方法

错误解析与修复方案

错误含义

你看到的[UserSession] maps short session requested but session sharing is not enabled是系统附带的日志提示,核心问题并非session共享未启用,而是你的路线请求本身无效——代码中起点和终点使用了完全相同的坐标,MapKit无法生成任何有效路线,因此触发了这个系统日志。

修复步骤

  1. 设置不同的起点与终点坐标
    这是最关键的修复点,MapKit无法为相同的起点和终点计算路线。修改代码中的坐标值,确保起点和终点是两个不同的有效位置:

    MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
    
    // 起点坐标
    CLLocationCoordinate2D sourceCoord = CLLocationCoordinate2DMake(35.0, 1.0);
    MKPlacemark *sourcePlacemark = [[MKPlacemark alloc] initWithCoordinate:sourceCoord addressDictionary:nil];
    request.source = [[MKMapItem alloc] initWithPlacemark:sourcePlacemark];
    
    // 终点坐标(与起点不同)
    CLLocationCoordinate2D destCoord = CLLocationCoordinate2DMake(35.1, 1.1);
    MKPlacemark *destPlacemark = [[MKPlacemark alloc] initWithCoordinate:destCoord addressDictionary:nil];
    request.destination = [[MKMapItem alloc] initWithPlacemark:destPlacemark];
    
    request.requestsAlternateRoutes = YES;
    MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
    
    [directions calculateDirectionsWithCompletionHandler:
           ^(MKDirectionsResponse *response, NSError *error) {
          if (error) {
            NSLog(@"路线请求失败:%@", error.localizedDescription);
          } else {
            NSLog(@"获取路线成功,路线数量:%lu", (unsigned long)response.routes.count);
          }
    }];
    
  2. 修正代码语法错误
    原代码中request.source和request.destination行末尾有多余的分号(;;),虽然不影响编译,但建议修正以保持代码规范。

  3. 确保位置权限配置正确
    即使手动设置坐标,MapKit的部分功能仍可能依赖位置权限。在Info.plist中添加以下权限描述之一:

    • NSLocationWhenInUseUsageDescription:应用在前台使用位置时的权限说明
    • NSLocationAlwaysAndWhenInUseUsageDescription:应用在前后台使用位置时的权限说明

内容的提问来源于stack exchange,提问作者gannonbarnett

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 10:10:52