最近在做一个文件管理类App,对FileManager做了些深入的了解,故总结整理出来,留作参考。
先介绍一些基础概念
-
硬链接(hard link)
-
软链接(又称符号链接,即soft link 或 symbolic link)
详细解释可参考 理解 Linux 的硬链接与软链接 -
Apple File System
从iOS 10.3 开始,Apple File System 替代 HFS Plus 成为了默认的文件系统。Apple File System 在多个方面做了优化,比如文件复制。
Tips
一般来说,文件相关的操作,FileManager 能够满足我们的需求。
// 创建硬链接
func linkItem(at srcURL: URL,
to dstURL: URL) throws
// 判断当前文件是否存在硬链接
// 如果返回结果 >=2,那就表明存在硬链接
fileURL.resourceValues(forKeys: [.linkCountKey])
注意,如果源文件路径为 App Bundle 中的资源,那么会创建失败NSCocoaErrorDomain 513 error (Operation could not be completed. Operation not permitted.)。
// 创建软链接
func createSymbolicLink(atPath path: String, withDestinationPath destPath: String) throws
// 判断是否为软链接
fileSymURL.resourceValues(forKeys: [.isSymbolicLinkKey])
// 获取原始文件路径
fileSymURL.resolvingSymlinksInPath()
/*
例如原始路径:
file:///var/containers/Bundle/Application/0EC8B47A-3975-43C0-95CE-498DAE111680/FileTest.app/1KB
软链接路径:
file:///var/mobile/Containers/Data/Application/A5EBFF94-2235-40F9-A414-43295B5DDEDC/Documents/1KB_symlink
*/
与硬链接不同的是,即使源文件路径为 App Bundle 中的资源,软链接也能创建成功。