-1

I am trying to use the function made by Martin R as an answer to this question: Get terminal output after a command swift

However, the UnsafePointer line no longer works with Swift 3 and I'm having trouble figuring it out. How would I adapt this code to Swift 3?

if var string = String.fromCString(UnsafePointer(outdata.bytes)) {
    string = string.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())
    output = string.componentsSeparatedByString("\n")
}

ps, You need to "Import Cocoa" if you want to trying using the function.

Community
  • 1
  • 1
Narwhal
  • 744
  • 1
  • 8
  • 22
  • Thinking about the referenced code again, using `String.fromCString()` there was perhaps not the best solution. I'll update that later. – Martin R Oct 26 '16 at 12:23

1 Answers1

2

In Swift 3, readDataToEndOfFile() returns a Data value, not NSData. The answer to your direct question would be

let data: Data = ...
let string = data.withUnsafeBytes { String(cString: UnsafePointer<CChar>($0)) }

However, that requires a NUL-terminated sequence of bytes (so that wasn't my smartest idea in Get terminal output after a command swift and I'll update that later).

Better use String(data: encoding:):

let outdata = outpipe.fileHandleForReading.readDataToEndOfFile()
if var string = String(data: outdata, encoding: .utf8) {
    string = string.trimmingCharacters(in: .newlines)
    output = string.components(separatedBy: "\n")
}
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382