0

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()
    }
}
Andrew
  • 1,088
  • 10
  • 21
  • Have you tested in on the main queue when you don't run under Xcode? I would be surprised if it worked on any queue. – Paulw11 Oct 25 '20 at 00:31
  • @Paulw11 I just tested it by tap the app icon, it worked both in foreground & back ground perfectly when on main queue DispatchQueue.main.async { self.startServer() } – Andrew Oct 25 '20 at 01:47

0 Answers0