Search code examples
xcodeprotocolsxpcswift2nsxpcconnection

NSXPCInterface constructor does not recognise protocol in Swift


I'm creating a XPC service in swift, and I created my protocol:

protocol MyProtocol {

func myFunc()

}

When I try to set the interface that the exported object implements (in my main.swift), by initialising a new object of NSXPCInterface with protocol, I get an error:

/// This method is where the NSXPCListener configures, accepts, and resumes a new incoming NSXPCConnection.
func listener(listener: NSXPCListener, shouldAcceptNewConnection newConnection: NSXPCConnection) -> Bool {
    // Configure the connection.
    // First, set the interface that the exported object implements.
    newConnection.exportedInterface = NSXPCInterface(MyProtocol)

Error is: Cannot convert value of type '(MyProtocol).Protocol' (aka 'MyProtocol.Protocol') to expected argument type 'Protocol'

Can anyone help me with this error?


Solution

  • To reference the protocol's type, you need to use .self on it:

     newConnection.exportedInterface = NSXPCInterface(withProtocol: MyProtocol.self)
    

    You also have to add @objc to your protocol declaration:

    @objc protocol MyProtocol {
        // ...
    }