【问题标题】:Firebase Cloud Functions response error iOSFirebase Cloud Functions 响应错误 iOS
【发布时间】:2026-02-18 21:35:01
【问题描述】:

我想使用 Firebase Cloud Functions,所以我从简单的“Hello world”示例开始作为后端部分,并从直接从应用调用函数的 iOS 示例开始。

云功能:

export const helloWorld = functions.https.onRequest((request, response) => {
    response.send('{"response":"Hello world"}') //option3
    response.send('Hello world');//option2
    response.send("Hello world");//option1 as in docs
});

我尝试了 3 种不同的响应选项。控制台说它有效。如果在浏览器中打开函数 url,它会打印“Hello world”。

iOS部分:

[[_functions HTTPSCallableWithName:@"helloWorld"] callWithObject:nil
  completion:^(FIRHTTPSCallableResult * _Nullable result, NSError * _Nullable error) {
      if (error) {
          if (error.domain == FIRFunctionsErrorDomain) {
              NSLog(@"domain code %ld@, details %@", error.code, error.userInfo[FIRFunctionsErrorDetailsKey] );
          }
          NSLog(@"code %ld, message %@, details %@", error.code,error.localizedDescription, error.userInfo[FIRFunctionsErrorDetailsKey]);
          return;
      }
      NSLog(@"result: %@", result.data);
 }];

它返回(在 3 个选项中的每一个中):代码 3840,消息无法读取数据,因为它的格式不正确。,详细信息(空)

如果响应格式一直由 Firebase 处理,我该怎么办?

【问题讨论】:

    标签: ios firebase google-cloud-functions


    【解决方案1】:

    为了成功,您需要以数据键格式将数据发送回字典。至少在 iOS 中是这样。在浏览器中,您可以以任何格式发回。

    例如:

    response.send({ data = {"response":"Hello world"}})

    【讨论】:

      【解决方案2】:

      在您的函数代码中,您创建常规 HTTPS 触发函数 (https.onRequest),对于可调用对象,您需要改用 https.onCall

      使用 Callables 的好处是它们会为您处理授权部分(对于常规 HTTPS 触发器,您需要编写自己的代码来验证用户身份)。

      Callables 的缺点是它们必须遵循特定的协议。虽然应该仍然能够从 Callables 返回任何 JSON 可序列化数据。

      如果您不需要身份验证,则可以使用常规 HTTPS 触发器,并且无需使用 SDK 即可简单地发送常规 HTTP 请求。

      阅读有关可调用对象的更多信息:https://firebase.google.com/docs/functions/callable

      【讨论】: