Safari扩展程序与包含应用程序的通信

时间:2018-10-04 10:06:01

标签: swift macos safari messaging

我有一个简单的Java应用程序,它从stdin a读取并写入stdout“您的消息是$ {line}”。

fun main(args: Array<String>) {
  val console = Scanner(System.`in`)
  while(console.hasNext()) {
    val message = console.next()
    println("Your message is $message")
    if(message == "quit"){
      break
    }
  }
}

然后我要在我的野生动物园扩展程序中使用此应用程序。 我已将此应用放在Singleton类的任务内

import Foundation
public class Messenger {
    let task = Process()
    let sksjStdin = Pipe()
    let sksjStdout = Pipe()
    static let shared = Messenger()

    init() {
        task.launchPath = "/usr/bin/java"
        task.currentDirectoryPath = "/Users/username"
        task.arguments = ["-jar", "./hello.jar"]
        task.standardInput = sksjStdout
        task.standardOutput = sksjStdin


    }

    public func start() {
        self.task.launch()
    }

    public func stop(){

        self.task.terminate()
    }

    public func sendMessage(message : String) -> String {
        self.sksjStdin.fileHandleForWriting.write(message.data(using: .utf8)!)
        var response = Data()
        repeat{
            response = sksjStdout.fileHandleForReading.availableData
        } while (response.count == 0)

        return String(data : response, encoding: .utf8)!
    }


};

我已经在AppDelegate中添加了启动服务的代码

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        Messenger.shared.start()
        // Insert code here to initialize your application
    }

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


}

然后我想通过Safari扩展处理程序将消息传递到此应用程序,但我不能这样做。 我在扩展程序中使用了此类代码

Messenger.shared.sendMessage(message : "hello from extension")

在XCode调试中挂起

response = sksjStdout.fileHandleForReading.availableData

我是macOS编程的新手。也许有人可以解释什么错 谢谢

0 个答案:

没有答案
相关问题