【问题标题】:Implement gRPC in an iOS React Native app在 iOS React Native 应用中实现 gRPC
【发布时间】:2017-12-11 06:01:27
【问题描述】:

this issue 中所述,我们无法使用 Node 实现来实现 gRPC 客户端,因为“RN 不是纯 Node”。

因此,我开始使用 Native Modules 进行 Objective-C 实现。

[service postWithRequest:request handler:^(RequestConfirmation * _Nullable response, NSError * _Nullable error) {
    if (response) {
        // This prints correctly in my JS console
        RCTLogInfo(@"%@", response.message);

        // This generates an error, see below
        resolve(response);

        // This works
        NSDictionary *formattedResponse = @{
            @"id": response.id_p,
            @"message": response.message
        };
        resolve(formattedResponse);
    } else {
        reject(@"error", @"An error occurred while saving", error);
    }
}];

错误:

RCTJSONStringify() encountered the following error: Invalid type in JSON write (RequestConfirmation)

如您所见,问题出在resolve 方法上。我想 React 没有找到任何方法将我的原始消息转换为 JSON。

如何保持响应不变并将其传递给 resolve 方法? 然后我可以在我的 JS 代码中对其进行解码。

谢谢。

编辑 1:

RequestConfirmation 在我的proto 文件中定义如下:

message RequestConfirmation {
    string id = 1;
    string message = 2;
}

然后在Objective-C中生成:

@interface RequestConfirmation : GPBMessage

@property(nonatomic, readwrite, copy, null_resettable) NSString *id_p;

@property(nonatomic, readwrite, copy, null_resettable) NSString *message;

@end

【问题讨论】:

    标签: node.js react-native protocol-buffers grpc react-native-ios


    【解决方案1】:

    也许以下是一个潜在的解决方案。

    Improbable Engineering已编码:

    • grpc-web - Typescript/Javascript、浏览器或 NodeJS!

    除了不幸的命名,这似乎不是仅仅是the official, C++-using, grpc-web project的一个分支。

    引用Improbable项目自己的grpc-web-client页面:

    此库适用于浏览器或 Node.js 中的 JavaScript 和 TypeScript

    Improbable 版本的可能好处似乎是:

    1. 它似乎没有使用本机代码(即 no C/C++/Java)
    2. 它可以为 Node.JS 生成 Typescript(因此是 JavaScript)

    所以,也许,当第 2 点与 NodeJS-on-RN 项目(例如 rn-nodeify)结合时,我们可以让 GRPC-on-RN 工作。

    如果您对此有任何成功,请提供反馈。

    【讨论】:

      【解决方案2】:

      在撰写本文时,Improbable Engineering's gRP-Web 不能与 React Native 一起使用。

      相反,您必须使用 React Native Native Modules 并在 Swift 或 Objective-C 中构建本机模块。由于 React Native 不直接与 Swift 对话,因此如果您选择使用 Swift,则必须创建一个 Objective-C 桥。

      你会:

      1. 以设备的本地语言实现 gRPC 客户端,
      2. 使用 React Native 的 Native 模块框架将其导出
      3. 通过 React Native 访问原生模块及其 gRPC 方法
      4. 在 React 你的 Native 代码中调用那些导出的方法

      这种关系的基本结构是:

      # Swift project
      Reat Native <-> ObjC Bridge <-> Swift <-> gRPC
      
      # Objective-C project
      Reat Native <-> ObjC <-> gRPC
      

      这是一个关于如何集成这些组件的相当长的解释。我为Building a gPRC Client in React Native on iOS/Swift 写了一个教程。我希望人们觉得这很有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-06
        • 1970-01-01
        • 2020-01-03
        • 1970-01-01
        • 2016-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多