假设文件URL
包含/Users/me/a/b
。有没有比使用NSHomeDirectory()
替换天真字符串更好的方法来获取短格式~/a/b
?
这就是我目前使用的
.replacingOccurrences(of: NSHomeDirectory(), with: "~", options: .anchored, range: nil)
PS:没有NSString
施法!
答案 0 :(得分:0)
如何转换为NSString然后用以下内容缩写:
var path = url.path as NSString!
var abbrevPath=path?.abbreviatingWithTildeInPath
答案 1 :(得分:0)
NSPathUtilities - (NSString *)stringByAbbreviatingWithTildeInPath; - (NSString *)stringByExpandingTildeInPath;
app.module.ts
答案 2 :(得分:0)
如果您在沙盒应用程序中,则需要使用getpwuid
函数。
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
}
}
用法示例:
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
}
有关getpwuid
函数的更多信息:How do I get the users home directory in a sandboxed app?
在NSView
中的使用结果:
答案 3 :(得分:0)
我注意到此问题尚未得到接受,我遇到了同样的问题。我尝试了NSString
方法,但是无论如何这些方法在沙盒环境中都不起作用,并且getpwuid
方法感到……是错误的。因此,这是一个纯粹的Swift解决方案,仅在假定沙箱根与实际主目录共享前三个路径组件(/
,Users
,用户名)的情况下,才进行真正的硬编码:
extension URL {
var pathAbbreviatingWithTilde: String {
// find home directory path (more difficulty because we're sandboxed, so it's somewhere deep in our actual home dir)
let sandboxedHomeDir = FileManager.default.homeDirectoryForCurrentUser
let components = sandboxedHomeDir.pathComponents
guard components.first == "/" else { return path }
let homeDir = "/" + components.dropFirst().prefix(2).joined(separator: "/")
// replace home dir in path with tilde for brevity and aesthetics
guard path.hasPrefix(homeDir) else { return path }
return "~" + path.dropFirst(homeDir.count)
}
}