Swift gRPC 客户端

Version License Platform

客户端库,依赖于 SwiftGRPC,这是一个用 Swift 编写的 gRPC 库。 基本上,它使用 SwiftGRPCCore 部分的功能,但目的是为了简化客户端的实现。


⚠️ 警告: 如果 SwiftGRPC 中存在重大更改,则此库可能无法更新。


包含以下两个模块。

SwiftGRPCClient

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

protoc-gen-swiftgrpc-client

这是一个 Protocol Buffer 插件,用于创建使用 SwiftGRPCClient 所必需的函数。 使用 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
}

这样,当使用某个请求进行连接时,需要一个特殊的方法来执行该请求。

使用 SwiftGRPCClientdata 是创建 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 文档。

要求

如何安装

CocoaPods

将以下内容添加到您的 Podfile

pod 'SwiftGRPCClient'

protoc-gen-swiftgrpc-client

protoc-gen-swiftgrpc-client 是一个 Protocol Buffers 的插件。 它自动定义了使用 SwiftGRPCClient 进行连接时使用的请求、响应和方法。

另请参阅 protoc-gen-swiftgrpc-client 文档。

要求

如何获取插件

执行以下命令。

$ 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 文件。