How to execute terminal commands in Swift 4?

2019-08-21 01:58发布

问题:

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