Overview
The swiftgrpcclient package is a Swift gRPC client library for communicating with gRPC servers. It allows you to easily connect to gRPC servers, perform RPC calls, and handle responses in your Swift applications.
Features
- Simple and intuitive API for gRPC communication.
- Supports both unary and server-streaming RPCs.
- Automatic serialization and deserialization of messages.
- Compatible with both Swift and Objective-C codebases.
- Built-in support for error handling and timeout management.
Installation
To use swiftgrpcclient in your Swift project, you can either manually add the package as a dependency or use a package manager like Swift Package Manager or CocoaPods.
Manual Installation
To manually add swiftgrpcclient to your project:
- Download the latest release from the GitHub repository.
- Copy the library files into your Xcode project’s directory.
- Add the library files to your Xcode project by right-clicking on your project’s “Frameworks” or “Libraries” group and selecting “Add Files”.
- Make sure the library files are properly added to your target and included for building.
Usage
Initialization
To start using swiftgrpcclient, you need to initialize a `GRPCClient` instance with the server’s address and gRPC service information:
let client = GRPCClient(address: "example.server.com", service: "example.Service")
Performing RPC Calls
Once the client is initialized, you can perform RPC calls to the server:
client.performUnaryRPC(callName: "exampleCall", request: requestMessage) { response, error in
if let response = response {
// Handle successful response
} else if let error = error {
// Handle error
}
}
Error Handling
The swiftgrpcclient library provides built-in error handling. If an error occurs during an RPC call, the error will be passed in the completion block:
client.performUnaryRPC(callName: "exampleCall", request: requestMessage) { response, error in
if let response = response {
// Handle successful response
} else if let error = error {
// Handle error
}
}
Examples
Example 1: Performing Unary RPC Call
This example demonstrates how to perform a unary RPC call using swiftgrpcclient:
let requestMessage = ExampleRequest() // Create your request message
client.performUnaryRPC(callName: "exampleCall", request: requestMessage) { response, error in
if let response = response {
// Handle successful response
} else if let error = error {
// Handle error
}
}
Example 2: Server-Streaming RPC
This example shows how to perform a server-streaming RPC call:
let requestMessage = ExampleRequest() // Create your request message
let responseHandler: (ExampleResponse?, Error?) -> () = { response, error in
if let response = response {
// Handle response
} else if let error = error {
// Handle error
}
}
let call = client.performServerStreamingRPC(callName: "exampleStreamingCall", request: requestMessage, responseHandler: responseHandler)
// You can use `call` to control the ongoing streaming, e.g., cancel it if needed
// call.cancel()