Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly used NSGetExecutablePath

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?

like image 353
Peter71 Avatar asked Aug 19 '15 08:08

Peter71


2 Answers

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!
like image 67
vadian Avatar answered Nov 11 '22 11:11

vadian


In Swift 4

let executablePath = Bundle.main.executablePath!
print(executablePath)
like image 31
Naresh Avatar answered Nov 11 '22 11:11

Naresh