3

Sorry if this is an answered question but 'Swift' 'App' and 'Protocol' are all too generic terms to warrant a good result.

I have socket emulator app that I use for testing that has a App struct with the server as a property:

@main
struct RelayEmulatorApp: App {

   var socketServer : SocketServer


   @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
}

And then in my appDelegate I override applicationWillTerminate where I would like to gracefully close the socket server. I'm finding since the socketServer's deinit has the calls to NIO's syncShutdownGracefully which is not called on app termination, I have to call it explicitly in AppDelegate (the OS apparently is slow to close the socket for a terminated process when the process doesn't do so--I think).

class AppDelegate: NSObject, NSApplicationDelegate {

  func applicationWillTerminate(_ notification: Notification) {

  }

}

But how in the AppDelegate can I reference the instance of the App struct (which I imagine is being instantiated by the @main annotation) and thus its properties to gracefully shutdown the socket?

Scott
  • 1,034
  • 1
  • 9
  • 19
  • Does this answer your question https://stackoverflow.com/a/63597866/12299030? – Asperi Jun 04 '21 at 11:31
  • Well, it could but I think I prefer Tarun Tyagi's solution of injecting the bits needed over depending on a singleton GOD AppState object as suggested in that solution. – Scott Jun 05 '21 at 16:45

1 Answers1

0

Inside the RelayEmulatorApp, after the socketServer has been instantiated, you can assign it to the appDelegate variable.

@main
struct RelayEmulatorApp: App {

   var socketServer : SocketServer

   @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

   func someFunctionThatInstantiatesSocketServer() {
       /// Instantiation for sockectServer is done at this point
       appDelegate.socketServer = socketServer
   }
}

Then you will have access to this instance in AppDelegate class.

class AppDelegate: NSObject, NSApplicationDelegate {

  var socketServer : SocketServer

  func applicationWillTerminate(_ notification: Notification) {
      /// socketServer.close() 
  }

}
Tarun Tyagi
  • 9,364
  • 2
  • 17
  • 30