Skip to content

Instantly share code, notes, and snippets.

@acalism
Last active November 23, 2017 03:34
Show Gist options
  • Select an option

  • Save acalism/5dc52f9aaefcee2616a9d619c78f7d6a to your computer and use it in GitHub Desktop.

Select an option

Save acalism/5dc52f9aaefcee2616a9d619c78f7d6a to your computer and use it in GitHub Desktop.
pitfall when converting file url to path
// 1. file url 与 path 转换
let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory())
let path = tmpURL.path //
// 事实上,tmpURL.absoluteString得到的是 file:// 格式,而path是没有协议(scheme)部分的,应以slash开头。
// 2. 检查文件存在性
let dir = (FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first ?? URL(fileURLWithPath: NSTemporaryDirectory())).appendingPathComponent("trackLog", isDirectory: true)
// 检查目录存在性,不存在就创建
var isDir: ObjCBool = false
// if let existed = try? dir.checkResourceIsReachable(), existed {} // 用url检查资源存在性(只用于file url)
if FileManager.default.fileExists(atPath: dir.path, isDirectory: &isDir) { // 用path检查资源存在性
print(isDir)
} else {
do {
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
}
@acalism
Copy link
Copy Markdown
Author

acalism commented Nov 23, 2017

这是一个常见陷阱

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment