【问题标题】:Unable to get XPC to receive data from the client无法让 XPC 接收来自客户端的数据
【发布时间】:2019-09-09 11:04:56
【问题描述】:

我正在尝试获取一个简单的命令行 Swift 应用程序,该应用程序稍后将用于与 Chrome\Firefox 进行本机消息传递,以与工作场所的其他应用程序进行通信。

主 UI 应用(即 XPC 服务器):

//
//  AppDelegate.swift
//

import Cocoa
import IOKit.ps
import Foundation
import Dispatch

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        let queue = DispatchQueue(label: "com.my.label");
        let conn:xpc_connection_t = xpc_connection_create_mach_service("com.test.xpc", queue, UInt64(XPC_CONNECTION_MACH_SERVICE_LISTENER));
        DispatchQueue.main.async {
            xpc_connection_set_event_handler(conn) { [weak self] client in
                debugPrint("client", client);
                xpc_connection_set_event_handler(client) { [weak self] object in
                    debugPrint("server received message:", xpc_copy_description( object ));
                }
                xpc_connection_resume(client);
            }
            print("inside dispatch");
            xpc_connection_resume(conn);
        }
        debugPrint("here after listener")
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

}

命令行应用程序(即 XPC 客户端)

//
//  main.swift
//

import Foundation
import XPC

let queue = DispatchQueue(label: "com.my.queue");
let conn:xpc_connection_t = xpc_connection_create_mach_service("com.test.xpc", queue, 0);

DispatchQueue.main.async {
    xpc_connection_resume(conn);
}

var message:xpc_object_t  = xpc_dictionary_create(nil, nil, 0 );
xpc_dictionary_set_string( message, "message", "hello world" );

xpc_connection_send_message(conn, message);

debugPrint("Exiting")

当我运行命令行应用程序时,服务器没有收到任何消息,所以我猜测客户端应用程序没有找到它或者服务器没有正确设置。

有什么建议吗?

谢谢

【问题讨论】:

    标签: swift macos xpc mach


    【解决方案1】:

    也许是这样的:

    用户界面:

    let queue = DispatchQueue(label: "com.my.label");
    

    命令行界面:

    let queue = DispatchQueue(label: "com.my.queue");
    

    你不应该使用同一个队列吗?

    【讨论】:

      【解决方案2】:

      Mach 服务不能按需从代码中注册,它们必须在程序的launchd 属性列表中的MachServices 条目中定义。但是,从根本上说,我怀疑您对 XPC Mach 服务的工作方式存在误解,因为几乎总是命令行工具将充当服务器(尽管这不是硬性要求)。

      【讨论】:

        猜你喜欢
        • 2019-01-24
        • 2013-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多