Skip to content

Instantly share code, notes, and snippets.

@andriitishchenko
Last active April 26, 2024 22:54
Show Gist options
  • Select an option

  • Save andriitishchenko/8cc4aea53b7b385adc60966933bb2ee0 to your computer and use it in GitHub Desktop.

Select an option

Save andriitishchenko/8cc4aea53b7b385adc60966933bb2ee0 to your computer and use it in GitHub Desktop.
Swift gRPC + Python server

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

brew install protobuf swift-protobuf grpc-swift

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

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

Swift

grpc/examples/protos/helloworld.proto

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
File->Swift Packages->Add Package Dependency
https://github.com/grpc/grpc-swift

Add GRPC to your 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 = "SwiftUI"
        }
        
        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)
            }
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment