通过执行Task冻结了GUI

时间:2019-06-06 18:15:46

标签: swift xcode bash macos

我有一个执行一些bash脚本的小应用程序。我已经有一个例行程序,到目前为止,它已经可以正常工作了。但是.... GUI在每次执行脚本时都会冻结。这是我已经拥有的:

func syncShellExec(path: String, args: [String] = []) {
    let process            = Process()
    process.launchPath     = "/bin/bash"
    process.arguments      = [path] + args
    let outputPipe         = Pipe()
    let filelHandler       = outputPipe.fileHandleForReading
    process.standardOutput = outputPipe

    filelHandler.readabilityHandler = { pipe in
        let data = pipe.availableData
        if let line = String(data: data, encoding: .utf8) {
            DispatchQueue.main.async {
                self.logger.string += line
            }
        } else {
            print("Error decoding data: \(data.base64EncodedString())")
        }
    }

    process.launch()
    process.waitUntilExit()
    filelHandler.readabilityHandler = nil
}

我想要这样:

    var task:Process!
    var out:FileHandle?
    var outputTimer: Timer?

    let path = "/bin/bash"
    let workDir = "/Users/luigi/Desktop"
    let arguments = "source"
    let arguments = ["backup.sh", arguments]
    task = Process.init()
    task.launchPath = path
    task.arguments = arguments
    task.currentDirectoryPath = workDir
    self.task.launch()
    DispatchQueue.global().async {
        // this runs in a worker thread, so the UI remains responsive
        print ("wating for exit")
        self.task.waitUntilExit()
        DispatchQueue.main.async {
            // do so in the main thread
            if let timer = self.outputTimer {
                timer.invalidate()
                self.outputTimer = nil
            }
        }
    }

我该怎么做才能将下部功能的非冻结部分集成到上部功能中?

0 个答案:

没有答案