我有一个窗口应用程序,要添加一些功能,我需要另一个应用程序,它在登录时启动并将数据同步到服务器(如果有)。
我尝试过使用 NSDistributionNotification,但它在沙盒应用程序中几乎没有用。我查看了 XPC 并希望它能够工作,但我只是不知道如何让它与助手一起工作。到目前为止,我已经使用 XPC 完成了这项工作。
主应用
NSXPCInterface *remoteInterface = [NSXPCInterface interfaceWithProtocol:@protocol(AddProtocol)];
NSXPCConnection *xpcConnection = [[NSXPCConnection alloc] initWithServiceName:@"com.example.SampleService"];
xpcConnection.remoteObjectInterface = remoteInterface;
xpcConnection.interruptionHandler = ^{
NSLog(@"Connection Terminated");
};
xpcConnection.invalidationHandler = ^{
NSLog(@"Connection Invalidated");
};
[xpcConnection resume];
NSInteger num1 = [_number1Input.stringValue integerValue];
NSInteger num2 = [_number2Input.stringValue integerValue];
[xpcConnection.remoteObjectProxy add:num1 to:num2 reply:^(NSInteger result) {
NSLog(@"Result of %d + %d = %d", (int) num1, (int) num2, (int) result);
}];
XPC服务
In main () ...
SampleListener *delegate = [[SampleListener alloc] init];
NSXPCListener *listener = [NSXPCListener serviceListener];
listener.delegate = delegate;
[listener resume];
// In delegate
-(BOOL)listener:(NSXPCListener *)listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection {
NSXPCInterface *interface = [NSXPCInterface interfaceWithProtocol:@protocol(AddProtocol)];
newConnection.exportedInterface = interface;
newConnection.exportedObject = [[SampleObject alloc] init];
[newConnection resume];
return YES;
}
// In Exported Object class
-(void)add:(NSInteger)num1 to:(NSInteger)num2 reply:(void (^)(NSInteger))respondBack {
resultOfAddition = num1 + num2;
respondBack(resultOfAddition);
}
这工作正常,现在我需要将此结果传递给 Helper 应用程序。我怎样才能做到这一点 ?如果 XPC 不是这里交流的答案,那么我应该使用哪一个?请问有什么指点吗?