Skip to content

Instantly share code, notes, and snippets.

@andriitishchenko
Last active April 26, 2024 22:54
Show Gist options
  • Save andriitishchenko/8cc4aea53b7b385adc60966933bb2ee0 to your computer and use it in GitHub Desktop.
Save andriitishchenko/8cc4aea53b7b385adc60966933bb2ee0 to your computer and use it in GitHub Desktop.
Swift gRPC + Python server

alt text

install protoc , protoc-gen-swift , protoc-gen-grpc-swift

brew install protobuf swift-protobuf grpc-swift grpcurl

Use examples

git clone --depth 1 --filter=blob:none --sparse https://github.com/grpc/grpc
cd grpc && git sparse-checkout set examples

Start Python server on a localhost

grpc/examples/python/helloworld/greeter_server_with_reflection.py <-- Server we need

cd grpc/examples/python/helloworld/
python3 -m pip install grpcio grpcio-tools grpcio-reflection
python3 greeter_server_with_reflection.py

Test the local server

grpcurl -plaintext -d '{"name": "TEST"}'  localhost:50051 helloworld.Greeter.SayHello

Swift

grpc/examples/protos/helloworld.proto <-- convert it to Swift

cd grpc/examples/protos/
protoc --swift_out=. --grpc-swift_out=Client=true,Server=false:. helloworld.proto

Import to Xcode files:

  • helloworld.grpc.swift
  • helloworld.pb.swift
Xcode->File->Swift Packages->Add Package Dependency
https://github.com/grpc/grpc-swift

Add GRPC to your app target

Swift Client example

import GRPC
import NIO
let conf = ClientConnection.Configuration.default(
    target:.hostAndPort("localhost", 50051),
    eventLoopGroup: MultiThreadedEventLoopGroup(numberOfThreads: 1))

let connection: ClientConnection = ClientConnection.init(configuration: conf)

let helloRequest = Helloworld_HelloRequest.with {
    $0.name = "Swift"
}

let client = Helloworld_GreeterNIOClient(channel: connection)

_ = client.sayHello(helloRequest).response.always { result in
    switch result {
    case let .success(helloResponse):
        print(helloResponse.message)
    case let .failure(error):
        print(error)
    }
}

More examples:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment