'MacOS swift: having trouble in obtaining output data from Pipe()

I am trying to run command lines to take screenshots in my Xcode project and using Pipe() to log output data. When I build and run this project in Xcode, I can get the output information as a string, like this screenshot's basic information. But when I archive this project as a MacOS applicaiton and run it, I get an error. I can't get any information for outputData.

The result of "outpipe.fileHandleForReading.readDataToEndOfFile()" is empty.

Here are my codes:

let task = Process()
task.launchPath = "/usr/sbin/screencapture"
var arguments = [String]();
arguments.append("-s") 
let ScreenshotPath = "screenshotpath.jpg"
arguments.append(ScreenshotPath)
task.arguments = arguments

let outpipe = Pipe()
task.standardOutput = outpipe
task.standardError = outpipe

do {
    try task.run()
} catch {
    print("error in process")
}
let outputData = outpipe.fileHandleForReading.readDataToEndOfFile()
let resultInformation = String(data: outputData, encoding: .utf8)
task.waitUntilExit()
print(resultInformation)

Can somebody help me with this out? Thank you so much!



Solution 1:[1]

I believe the issue is assigning your Pipe object to both task.standardOutput and task.standardError. I recommend creating two distinct Pipe objects, then passing them to the outputs respectively.

We used the function from this answer in production on the Mac App Store.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex