Search code examples
swiftvapornsapplication

Running NSApplication.shared alongside Vapor?


I want my Vapor app to be able to create and show NSWindows on the host machine. For this I've edited main.swift like this:

import AppKit
import App
import Vapor

var env = try Environment.detect()
try LoggingSystem.bootstrap(from: &env)
let app = Application(env)
defer { app.shutdown() }
try configure(app)

DispatchQueue.init(label: "com.myapp.vapor", qos: DispatchQoS.userInteractive).async {
    try! app.run()
}

NSApplication.shared.run()

So Vapor runs in a separate queue, while NSApplication runs in the main queue. This works, but I need to call DispatchQueue.main.async inside Vapor handlers, and I'd like to avoid it. Is it possible to extend Vapor application and set is as app delegate?


Solution

  • Vapor does not use Dispatch so I suspect you'll always need to wrap any calls that deal with UI in the DispatchQueue.main.async.

    One option would be to replace the DefaultResponder with something that puts request handling on the main loop. You'd need to work out how to make Dispatch and NIO play nice however. Another option is to call out to an app delegate in your route handlers that can then do what it likes on the main thread.