fileURL.resourceValues 是 macOS/iOS 中用于获取文件 URL 各种元数据属性(Resource Values)的方式之一,基于 URLResourceValues 类型。
基本用法
let resourceValues = try fileURL.resourceValues(forKeys: [.fileSizeKey, .isDirectoryKey])
fileURL 是一个指向文件或目录的 URL(必须是本地文件 file:// 类型)。
resourceValues(forKeys:) 会返回该 URL 的一组元数据(封装为 URLResourceValues属性)。
常用属性
可以从文件中读取的 URLResourceKey 列表:
1、.nameKey:属性name,文件名称。
2、.fileSizeKey:属性fileSize,文件大小(单位:字节)。
3、.isDirectoryKey:属性isDirectory,是否是目录。
4、.isRegularFileKey:属性isRegularFile,是否是常规文件。
5、.creationDateKey:属性creationDate,创建时间。
6、.contentModificationDateKey:属性contentModificationDate,最后修改时间。
使用场景
1、读取文件大小和名称
let fileURL = URL(fileURLWithPath: "/Users/you/Desktop/image.jpg")
do {
let values = try fileURL.resourceValues(forKeys: [.fileSizeKey, .nameKey])
if let size = values.fileSize, let name = values.name {
print("文件名: \(name)")
print("文件大小: \(size) 字节")
}
} catch {
print("读取文件属性失败: \(error)")
}
2、读取图片文件的Finder大小
let resourceValues = try? fileURL.resourceValues(forKeys: [.totalFileAllocatedSizeKey])
let DiskSize = resourceValues?.totalFileAllocatedSize ?? 0
因为图片文件在Finder和实际大小不一样,所以需要通过 . totalFileAllocatedSizeKey 键获取大小。相关内容请见《SwiftUI获取文件大小/占用空间》。
总结
通过URL的resourceValues方法,可以获取文件的元属性。
如果想要获取文件的实际磁盘占用,只能通过URL的resourceValues(forKeys:)获取。
