我有一对实现XPC主应用程序+服务应用程序模式的Swift Xcode目标。我找出了如何通过远程对象的方法参数或“返回值”(即完成处理程序/回复块的参数)来传递自定义类。这一切都很好地运作。
现在,我正在尝试添加一个新的细节:从服务中使用自定义类的NSArray调用完成处理程序,将它们返回到主应用程序。我从 Apple 的文档 (以及 这个 Obj-C 答案 )了解到,我需要在接收端的NSXPCInterface
上列出我的自定义类。但我无法弄清楚如何在Swift中执行此操作。所有在线和文档中的示例都是Obj-C,我很难找到正确的Swift等效项。
具体来说,这是我自定义类的简化版本:
@objc(PartialSnapshot) public class PartialSnapshot : NSObject, NSSecureCoding {
public var rawPaths: [String]
public static var supportsSecureCoding: Bool = true
public func encode(with coder: NSCoder) {
coder.encode(rawPaths, forKey: "rawPaths")
}
public required init?(coder: NSCoder) {
guard
let rawPaths = coder.decodeObject(of: [NSArray.self], forKey: "rawPaths") as? [String]
else {
NSLog("PartialSnapshot: returning nil from init?(coder: NSCoder)")
return nil
}
self.rawPaths = rawPaths
}
}
@objc(ReadAllSnapshotsRpcReturnType) public class ReadAllSnapshotsRpcReturnType : NSObject, NSSecureCoding {
var partials: [PartialSnapshot]
public static var supportsSecureCoding: Bool = true
public func encode(with coder: NSCoder) {
coder.encode(partials, forKey: "partials")
}
public required init?(coder: NSCoder) {
guard
let partials = coder.decodeObject(of: [NSArray.self], forKey: "partials") as? [PartialSnapshot]
else {
NSLog("ReadAllSnapshotsRpcReturnType: returning nil from init?()")
return nil
}
self.partials = partials
}
}
我在远程对象协议上的方法签名:
@objc func ReadAllSnapshotsRpc(then completion: @escaping (ReadAllSnapshotsRpcReturnType?, Error?) -> Void)
从这个Objective-C的答案中,我大致知道需要做什么。当我在主应用程序中创建NSXPCConnection
时,我需要添加像下面第三行那样的一行代码:
let connection = NSXPCConnection(machServiceName: SecurityProxyConstants.domain, options: .privileged)
connection.remoteObjectInterface = NSXPCInterface(with: SecurityProxyProtocol.self)
connection.remoteObjectInterface?.setClasses(ReadAllSnapshotsRpcReturnType.self, for: #selector(PartialSnapshot.self), argumentIndex: 0, ofReply: true)
然而,我很明显的语法并不完全正确,我尝试了许多不同的语法变化也无法编译。有人能指导我吗?
编辑:这是我遇到的运行时错误,让我相信我需要加入白名单:
<NSXPCConnection: 0x600003f5b0c0> connection to service with pid 9679 named com.mycompany.MyApp.SecurityProxy: Exception caught during decoding of reply to message 'ReadAllSnapshotsRpcWithThen:', dropping incoming message and calling failure block.
Ignored Exception: Exception while decoding argument 0 (#1 of invocation):
<NSInvocation: 0x600001bdb740>
return value: {v} void
target: {@?} 0x0 (block)
argument 1: {@} 0x0
argument 2: {@} 0x0
Exception: value for key 'NS.objects' was of unexpected class 'PartialSnapshot' (0x10c7abe00) [/Users/mwg/Library/Developer/Xcode/DerivedData/MyApp-brumjpaxvoxfmjchpswlfnbsarho/Build/Products/Debug/MyApp.app].
Allowed classes are:
{(
"'NSArray' (0x7ff8485798a0) [/System/Library/Frameworks/CoreFoundation.framework]"
)}