brew install protobuf swift-protobuf grpc-swift grpcurl
git clone --depth 1 --filter=blob:none --sparse https://github.com/grpc/grpc
cd grpc && git sparse-checkout set examples
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
grpcurl -plaintext -d '{"name": "TEST"}' localhost:50051 helloworld.Greeter.SayHello
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
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:
- https://medium.com/@thomsmed/5-tips-when-getting-started-with-grpc-and-ios-9e4323bd6b98
- https://mtanriverdi.medium.com/grpc-call-on-ios-with-swift-ef11d3151cbf
- https://gaitatzis.medium.com/building-a-grpc-client-in-ios-swift-3b0d36999678
- https://medium.com/@hardik.7091/guide-to-integrating-grpc-server-and-swift-client-32dc1a05aa8e
- https://levelup.gitconnected.com/swift-grpc-577ce1a4d1b7