If you are in Sandboxed app then usage of getpwuid
function is needed.
extension FileManager {
/// Returns path to real home directory in Sandboxed application
public var realHomeDirectory: String? {
if let home = getpwuid(getuid()).pointee.pw_dir {
return string(withFileSystemRepresentation: home, length: Int(strlen(home)))
}
return nil
}
}
Example usage:
func configure(url: URL) {
...
var directory = url.path.deletingLastPathComponent
toolTip = url.path
if let homeDir = FileManager.default.realHomeDirectory {
// FYI: `url.path.abbreviatingWithTildeInPath` not working for sandboxed apps.
let abbreviatedPath = url.path.replacingFirstOccurrence(of: homeDir, with: "~")
directory = abbreviatedPath.deletingLastPathComponent
toolTip = abbreviatedPath
}
directoryLabel.text = directory
}
More about getpwuid
function: How do I get the users home directory in a sandboxed app?
Result of usage in NSView
:
