How to execute terminal commands in Swift 4?

て烟熏妆下的殇ゞ 提交于 2020-01-15 10:14:30

问题


I have an iOS app and in the unit tests (XCTests) I need to execute some terminal commands such as xcrun simctl shutdown [simulator-UDID]

I created this function to run the shell scripts

func commandLine(launchPath: String, arguments: [String]) -> String {
    // Used to be NSTask() before Swift 3
    let process = Process()

    // Set the task parameters
    process.launchPath = "/usr/bin/env"
    process.arguments = ["pwd"]

    // Create a Pipe and make the process
    // put all the output there
    let pipe = Pipe()
    process.standardOutput = pipe

    // Launch the process
    process.launch()

    // Get the data
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = NSString(data: data, encoding: NSUTF8StringEncoding)

    print(output!)
}

However, I got the error saying that

Use of unresolved identifier 'Process'

Did some research and it turns out Process() has been renamed to CommandLine in Swift 4, but changing to CommandLine causes different error

'CommandLine' cannot be constructed because it has no accessible initializers

来源:https://stackoverflow.com/questions/46592871/how-to-execute-terminal-commands-in-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!