IOS: convert UnsafeMutablePointer <Int8> to string in swift?
Times have changed. In Swift 3+, you will do it like this:
If you want utf-8 to be checked:
let str: String? = String(validatingUTF8: c_str)
If you want utf-8 errors to be converted to a unicode error symbol:
let str: String = String(cString: c_str)
, c_str UnsafePointer<UInt8> UnsafePointer<CChar>, C.
let str: String? = String(validatingUTF8: c_str)
doesn't seem to work with UnsafeMutablePointer <UInt8> (this is what appears to be in my data).
This I am trivially figuring out how to do something like a C / Perl system function:
let task = Process()
task.launchPath = "/bin/ls"
task.arguments = ["-lh"]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
var unsafePointer = UnsafeMutablePointer<Int8>.allocate(capacity: data.count)
data.copyBytes(to: unsafePointer, count: data.count)
let output : String = String(cString: unsafePointer)
print(output)
//let output : String? = String(validatingUTF8: unsafePointer)
//print(output!)
if I switch to validatingUTF8 (with optional) instead of cString, I get this error:
./ls.swift:19:37: error: cannot convert value of type 'UnsafeMutablePointer<UInt8>' to expected argument type 'UnsafePointer<CChar>' (aka 'UnsafePointer<Int8>')
let output : String? = String(validatingUTF8: unsafePointer)
^~~~~~~~~~~~~
Thoughts on how to check out UTF8 on channel output (so that I don't get a Unicode error character anywhere)?
(yes, I am not doing a proper check of my optional print (), which is not the problem that I am solving now ;-)).