Last active
November 23, 2017 03:34
-
-
Save acalism/5dc52f9aaefcee2616a9d619c78f7d6a to your computer and use it in GitHub Desktop.
pitfall when converting file url to path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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) | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
这是一个常见陷阱