gRPC server stop receive requests when iOS app enter background

572 views Asked by At

I wanna run a gRPC Server in my iOS App, and my App maybe runs on background for a long time. It works fine when App is in the foreground mode, but in background mode, the gRPC Server will not response to any Client connection. And It will work again once App comes back to foreground.

If I start the Server on main thread, everything works fine. But I don't want to block my main thread.

Any help would be greatly appreciated!

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Move to a background thread to do some long running work
        DispatchQueue.global(qos: .userInitiated).async {
            self.startServer()
        }
        
    }
    
    func startServer() {
        let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
        defer {
          try! group.syncShutdownGracefully()
        }

        // Start the server and print its address once it has started.
        let server = Server.insecure(group: group)
          .withServiceProviders([GreeterProvider()])
          .bind(host: "0.0.0.0", port: 53442)
        
        server.map {
            $0.channel.localAddress
        }.whenSuccess { address in
          print("server started on port \(address!.port!)")
        }
        // Wait on the server's `onClose` future to stop the program from exiting.
        _ = try! server.flatMap {
            $0.onClose
        }.wait()
    }
}
0

There are 0 answers