Peter71
Peter71

Reputation: 2310

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?

Upvotes: 5

Views: 1930

Answers (2)

vadian
vadian

Reputation: 285290

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!

Upvotes: 5

Naresh
Naresh

Reputation: 17932

In Swift 4

let executablePath = Bundle.main.executablePath!
print(executablePath)

Upvotes: 1

Related Questions