如何将NSURL与相对路径一起使用



因此,我正在Swift中构建一个以文件路径为参数的命令行工具。我检查文件路径是否存在,否则会抛出错误。当我使用绝对路径时,一切都会正常工作。当我使用相对路径时,它不会。

代码:

let pwdURL = URL(string: "file://" + FileManager.default.currentDirectoryPath)
print("pwdURL: ", pwdURL ?? "no pwdURL")
let pathURL = URL(string: path, relativeTo: pwdURL)
print("pathURL: ", pathURL ?? "no pathURL")
do {
let _ = try pathURL?.checkResourceIsReachable()
}
catch {
print(error)
throw ValidationError("(path) Is not a valid path.")
}

命令:

/Users/myUser/Projects/myProject文件夹,在终端中。

swift run myProject ../../Downloads/myFile.pdf

输出:

pwdURL:  file:///Users/myUser/Projects/myProject
pathURL:  ../../Downloads/myFile.pdf -- file:///Users/myUser/Projects/myProject

Error Domain=NSCocoaErrorDomain Code=260 "The file “myFile.pdf” couldn’t be opened because there is no such file." UserInfo={NSURL=../../Downloads/myFile.pdf -- file:///Users/myUser/Projects/myProject, NSFilePath=/Users/Downloads/myFile.pdf, NSUnderlyingError=0x7fad39d0c280 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
Error: ../../Downloads/myFile.pdf Is not a valid path.

我希望它查找/Users/myUser/Downloads/myFile.pdf,因为这是我在终端中键入命令的有效路径。此外,当我查看pathURL(../../Downloads/myFile.pdf -- file:///Users/myUser/Projects/myProject(的输出时,它看起来会解析为正确的路径?但正如您所看到的,存在一个错误,因为它正在查找不存在的/Users/Downloads/myFile.pdf

relativeTo参数必须以/结尾,才能按预期方式工作。来自NSURL文档(重点添加(:

此方法允许您创建相对于基本路径或URL的URL。例如,如果您有磁盘上某个文件夹的URL和该文件夹中某个文件的名称,则可以通过提供文件夹的URL作为基本路径(带有尾部斜杠(和文件名作为字符串部分来构造该文件的URL。

所以你需要的是:

let pwdURL = URL(string: "file://" + FileManager.default.currentDirectoryPath + "/")

但我实际上会这样做:

let pwdURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)

或:

let pwdURL = Process().currentDirectoryURL

我通常发现使用appendingPathComponent更容易做到这一点,它更容易正确使用:

let pathURL = pwdURL.appendingPathComponenent(path)

不同的是,这将把../..留在路径中,而不是解决这些问题,所以这确实取决于你想要哪个。

最新更新