I try to get the path to my application at runtime. I found some old sources from C and converted it accordingly to the functions parameter type definition:
var path = [Int8] (count:1024, repeatedValue: 0)
var bufsize : UInt32 = 1024
if _NSGetExecutablePath(&path, &bufsize) == 0 {
println("executable path is \(path)")
}
It runs, but I need an Int8 array, not a string. So I have to search for the end of the character chain and convert it back to a string. What is the correct way to use this function in SWIFT?
You need to create a Swift String from a C String
let executablePath = String(CString: path, encoding: NSASCIIStringEncoding)!
println("executable path is \(executablePath)")
But there is an easier way to get the path to the executable
let executablePath = Bundle.main.executablePath!
In Swift 4
let executablePath = Bundle.main.executablePath!
print(executablePath)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With