gpt4 book ai didi

swift - 在 URL 中用波浪号替换用户路径

转载 作者:行者123 更新时间:2023-11-28 08:26:51 25 4
gpt4 key购买 nike

假设一个文件 URL 包含 /Users/me/a/b。有没有比使用 NSHomeDirectory() 获取短格式 ~/a/b 的简单字符串替换更好的方法?

这是我目前正在使用的

.replacingOccurrences(of: NSHomeDirectory(), with: "~", options: .anchored, range: nil)

PS: 没有 NSString 转换!

最佳答案

如果您在沙盒应用中,则需要使用 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 中的使用结果:

enter image description here

关于swift - 在 URL 中用波浪号替换用户路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39764037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com