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

React Native生产环境中Google逆地理编码功能失效问题排查

问题:Google地理编码API在iOS生产构建中请求失败,开发环境正常

我正在使用Google地理编码API根据地址获取经纬度。该功能在Expo开发环境中正常运行,但编译为iOS应用后请求失败。每次修改都要重新打包提交至TestFlight,调试难度极大,但用expo run:ios在模拟器中运行开发构建时功能正常。

目前函数仅返回undefined,Google Cloud控制台未显示任何错误。我已经将NSAllowsArbitraryLoads设为true,怀疑是iOS阻止了对googleapis.com的请求?

我的代码:

const fetchCoordinates = async () => {
  try {
    const apiKey = Util.getPlatformAPIKey();
    const googleApiUrl = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}&key=${apiKey}`;

    const response = await fetch(googleApiUrl, {
      mode: "no-cors",
      redirect: "follow",
      method: "GET",
    });

    if (!response.ok) {
      return;
    } else {
      setStatus("Response from geocoding API ok");
    }

    const data = await response.json();

    if (data.results.length > 0) {
      const {lat, lng} = data.results[0].geometry.location;
      return {latitude: lat, longitude: lng};
    } else {
      return undefined;
    }
  } catch (error) {
    console.error("Error fetching coordinates:", error);
  }
};

ATS配置:

"NSAppTransportSecurity": {
    "NSAllowsArbitraryLoads": true
}

解决方案

1. 移除mode: "no-cors"是核心修复点

你设置的mode: "no-cors"会强制运行时完全禁止读取响应内容——哪怕请求实际成功,response.ok也会始终返回false,更无法执行response.json()解析。开发环境因Expo调试代理的特殊机制绕过了这个限制,但生产构建会严格遵循CORS规则。

直接删除该配置项:

const response = await fetch(googleApiUrl, {
  redirect: "follow",
  method: "GET",
});

2. 确认ATS配置的正确位置

虽然你设置了NSAllowsArbitraryLoads: true,但在Expo项目中必须将其放在app.json的ios.infoPlist字段内才会生效:

{
  "expo": {
    "ios": {
      "infoPlist": {
        "NSAppTransportSecurity": {
          "NSAllowsArbitraryLoads": true
        }
      }
    }
  }
}

实际Google APIs均为HTTPS协议,该配置并非必需,移除后反而更安全。

3. 补充错误调试逻辑

当前代码在!response.ok时直接返回,没有任何错误日志,无法定位问题。修改为:

if (!response.ok) {
  console.error(`Geocoding API请求失败: ${response.status} ${response.statusText}`);
  const errorContent = await response.text();
  console.error("响应内容:", errorContent);
  return;
}

这样即使请求失败,也能获取到具体错误信息(如API密钥无效、地址格式错误、配额耗尽等)。

4. 检查API密钥的平台限制

登录Google Cloud控制台确认:

  • 已为该API密钥绑定你的iOS应用Bundle ID
  • 地理编码API已启用
  • 密钥的调用配额未耗尽

内容的提问来源于stack exchange,提问作者Zach B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 12:33:30