我有一个窗口应用程序,为了添加一些功能,我需要另一个应用程序,在登录时启动并在可用时将数据同步到服务器。
我试着使用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 app。我该怎么做?如果XPC不是通信的答案,那我应该使用哪种通信方式?请给我一些指导。