Replacing @protocol (<protocol name>) in swift

I am trying to use NSXPCConnection

in swift.

So this line:

_connectionToService = [[NSXPCConnection alloc] initWithServiceName:@"SampleXPC"];

      

can be replaced with this line:

_connectionToService = NSXPCConnection(serviceName: "SampleXPC")

      

And this line:

_connectionToService.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(StringModifing)];

      

can be replaced with this line:

_connectionToService.remoteObjectInterface = NSXPCInterface(protocol: <#Protocol#>)

      

Now I am confused about using the correct replacement for: <#Protocol#>

in swift, in lens c I would use: @protocol(StringModifing)

but in swift I don’t know :(

+3


source share


1 answer


This is a difficult question.

First of all, protocol is a reserved keyword and cannot be used as a parameter label. A quick inspection of Apple's official document helped me. use `protocol` instead. This means that the parameter name contains single quotes.

"[obj class]" is replaced with "obj.self" in swift. The same syntax is used for protocols. This means that in your case "@protocol (StringModifing)" becomes "StringModifing.self".



Unfortunately, this still won't work. The problem is behind the scenes now. The xpc engine is kind of low-level stuff and requires ObjC style protocols. This means that you need the @objc keyword before declaring the protocol.

Collectively, the solution:

@objc protocol StringModifing {

    func yourProtocolFunction()
}

@objc protocol StringModifingResponse {

    func yourProtocolFunctionWhichIsBeingCalledHere()
}

@objc class YourXPCClass: NSObject, StringModifingResponse, NSXPCListenerDelegate {

    var xpcConnection:NSXPCConnection!
    private func initXpcComponent() {

        // Create a connection to our fetch-service and ask it to download for us.
        let fetchServiceConnection = NSXPCConnection(serviceName: "com.company.product.xpcservicename")

        // The fetch-service will implement the 'remote' protocol.
        fetchServiceConnection.remoteObjectInterface = NSXPCInterface(`protocol`: StringModifing.self)


        // This object will implement the 'StringModifingResponse' protocol, so the Fetcher can report progress back and we can display it to the user.
        fetchServiceConnection.exportedInterface = NSXPCInterface(`protocol`: StringModifingResponse.self)
        fetchServiceConnection.exportedObject = self

        self.xpcConnection = fetchServiceConnection

        fetchServiceConnection.resume()

        // and now start the service by calling the first function
        fetchServiceConnection.remoteObjectProxy.yourProtocolFunction()
    }

    func yourProtocolFunctionWhichIsBeingCalledHere() {

        // This function is being called remotely
    }
}

      

0


source







All Articles