【问题标题】:"Bash like" paths to NSURL or Foundation pathNSURL 或 Foundation 路径的“Bash like”路径
【发布时间】:2017-10-31 10:17:35
【问题描述】:

在大多数命令行工具中,可以使用以下格式指定文件路径:../someFile~/anotherFile/foo/bar。如何从这样的路径初始化有效的 Swift URL 或(Foundation)路径?

编辑:
也许一个代码示例更清楚,比如我想从路径初始化一个字符串,并且我的用户目录中有一个 foo 文件,这样做:

try String(contentsOfFile: "~/foo")

不起作用(错误是文件不存在)

【问题讨论】:

  • init(fileURLWithPath path: String, relativeTo base: URL?) 最后一个?
  • @Larme Hum...如果我是对的,最后一个不是相对 URL(它只是指定放置在 /foo 文件夹中当前磁盘根目录的资源)跨度>
  • @MartinR - 这个答案现在已经过时了。

标签: swift foundation


【解决方案1】:

在 Swift 中,你可以这样做:

let str = "~/Documents"
// NSString has a function for decoding this, not available to String:
let str2 = (str as NSString).standardizingPath as String 

// Swift deprecated the String path manipulation functions,
// but supplies them as part of NSURL:
let url = URL(fileURLWithPath: str)
let url2 = url.standardizedFileURL // Expands the URL

【讨论】:

    猜你喜欢
    • 2014-12-27
    • 2011-10-02
    • 2012-08-17
    • 2013-01-06
    • 2014-10-16
    • 1970-01-01
    • 2014-02-15
    • 2014-08-30
    • 2012-02-17
    相关资源
    最近更新 更多