我正在尝试在swift中使用NSXPCConnection。
所以,这一行:
_connectionToService = [[NSXPCConnection alloc] initWithServiceName:@"SampleXPC"];可以替换为下面这一行:
_connectionToService = NSXPCConnection(serviceName: "SampleXPC")并且,这一行:
_connectionToService.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(StringModifing)];可以替换为下面这一行:
_connectionToService.remoteObjectInterface = NSXPCInterface(protocol: <#Protocol#>)现在我对在swift中使用:<#Protocol#>的正确替代方法感到困惑,在objective c中我会使用:@protocol(StringModifing),但在swift中我一无所知:(
发布于 2015-02-04 20:29:38
这是一个棘手的问题。
首先,协议是一个保留关键字,不能用作参数标签。快速浏览一下苹果官方文档对我很有帮助。请改用`协议。这意味着参数名称包含单引号。
在swift中,"obj class“正在被"obj.self”所取代。协议也使用相同的语法。这意味着在你的例子中,"@protocol(StringModifing)“变成了"StringModifing.self”。
不幸的是,这仍然不起作用。现在的问题是在幕后。xpc机制是一种低级的东西,需要ObjC风格的协议。这意味着您需要在协议声明之前使用关键字@objc。
总的来说,解决方案是:
@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
}
}发布于 2018-09-17 17:35:14
Swift 4
_connectionToService.remoteObjectInterface = NSXPCInterface(with: StringModifing.self)https://stackoverflow.com/questions/26291005
复制相似问题