gRPC-Client-Swift 1.0.0-alpha.8

gRPC-Client-Swift 1.0.0-alpha.8

Kyohei Ito 维护。



gRPC-Client-Swift 1.0.0-alpha.8

  • Kyohei Ito

Swift gRPC Client

Version License Platform

这是一个客户端库,取决于 SwiftGRPC,它是一个用 Swift 编写的 gRPC 库。基本上,它使用 SwiftGRPCCore 部分的功能,但它是为了让客户端实现更容易而构建的。


⚠️ 警告:如果有对 SwiftGRPC 的破坏性更改,此库可能无法更新。


以下包含两个模块。

SwiftGRPCClient

这是一个用于运行时使用的插件。将其链接到应用程序或框架。

protoc-gen-swiftgrpc-client

它是一个用于创建 SwiftGRPCClient 所需功能的 Protocol Buffer 插件。使用 protoc.proto 生成 .swift

SwiftGRPCClient

如果您使用了 SwiftGRPC,您可以像下面这样使用生成的 protocolstruct 来进行 Unary 连接。

let service = Echo_EchoServiceClient(address: "YOUR_SERVER_ADDRESS")
var requestMessage = Echo_EchoRequest()
requestMessage.text = "message"
_ = try? service.get(requestMessage) { responseMessage, callResult in
}

上面的 get 方法可以通过发送任意的 message 来获取 message,但使用此方法无法获取登录用户的详细信息。例如,如果您想获取用户信息,则需要准备以下方法。

var requestUser = Example_UserRequest()
requestUser.id = "user_id"
_ = try? service.getUser(requestUser) { responseUser, callResult in
}

以这种方式,在通过某种请求连接时,需要使用特殊方法来执行这个请求。

对于 SwiftGRPCClient 而言,data 是唯一用于发送 Unary 请求的方法。

let session = Session(address: "YOUR_SERVER_ADDRESS")
session.stream(with: EchoUnaryRequest(text: "message"))
    .data { result in
    }

只需要改变请求,就可以获取用户的登录信息。

session.stream(with: GetUserRequest(id: "user_id"))
    .data { result in
    }

有关更多信息,请参阅 SwiftGRPCClient 文档。

要求

  • Swift 5.0
  • SwiftGRPC 0.9.1

如何安装

CocoaPods

在您的 Podfile 中添加以下内容

pod 'SwiftGRPCClient'

protoc-gen-swiftgrpc-client

protoc-gen-swiftgrpc-client 是用于 Protocol Buffers 的一个插件。它会自动定义使用 SwiftGRPCClient 连接时所需的请求、响应及方法。

有关更多信息,请参阅 protoc-gen-swiftgrpc-client 文档。

要求

  • Swift 5.0
  • SwiftProtobuf 1.5.0

如何获取插件

执行以下命令。

$ make gen

说明生成的代码

例如,准备以下 .proto 文件。

syntax = "proto3";

package echo;

service Echo {
    rpc Get(EchoRequest) returns (EchoResponse) {}
}

message EchoRequest {
    string text = 1;
}

message EchoResponse {
    string text = 1;
}

protoc 生成 .swift 文件。

// MARK: - Echo Request Method
enum Echo_EchoMethod: String, CallMethod {
    case get = "Get"

    static let service = "echo.Echo"
}

// MARK: - Echo_Echo Get Request
protocol _Echo_EchoGetRequest {
    typealias InputType = Echo_EchoRequest
    typealias OutputType = Echo_EchoResponse
}

protocol Echo_EchoGetRequest: _Echo_EchoGetRequest, UnaryRequest {}

extension Echo_EchoGetRequest {
    var method: CallMethod {
        return Echo_EchoMethod.get
    }
}

在生成的 .swift 中使用 protocol 定义 Request 对象。

struct EchoGetRequest: Echo_EchoGetRequest {
    var request = Echo_EchoRequest()

    init(text: String) {
        request.text = text
    }
}

版权许可

根据 MIT 授权许可。详情请见 LICENSE 文件。