【问题标题】:Get the Attributes of every item in the Document Directory iOS Swift获取文档目录iOS Swift中每个项目的属性
【发布时间】:2019-08-11 00:05:52
【问题描述】:

我一直在尝试获取文档目录中所有项目的属性,例如文件类型、创建日期、文件大小。

这是我一直在使用的代码,但它只返回“NSFileTypeDirectory

 let filemgr = FileManager.default
        
        
     do
     {
        let attribs: NSDictionary? = try filemgr.attributesOfItem(
            atPath: documentDirectoryPath!) as NSDictionary
        if let fileattribs = attribs
     {
            let type = fileattribs["NSFileType"] as! String
            print("File type \(type)")
     }
     }
     catch
     {
            print(error)
     }

我认为它返回了 Document 文件夹的属性。

【问题讨论】:

  • 那是因为您传递的是 Documents Directory 的路径,而不是 documents directory 中文件的路径 。您需要在您想要属性的文档目录中传递文件的完整路径
  • 不相关但 attributesOfItem(atPath 返回非可选 [FileAttributeKey : Any] not 可选 NSDictionary 并且永远不会使用 error 变量。

标签: ios swift nsdocumentdirectory nsattributedescription


【解决方案1】:

试试这个

let fileManager = FileManager.default
let documentdirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first
let filePath = documentdirectory?.appendingPathComponent("your file name").path

do {
  let fileAttribute = try fileManager.attributesOfItem(atPath: filePath!)
  let fileSize = fileAttribute[FileAttributeKey.size] as! Int64
  let fileType = fileAttribute[FileAttributeKey.type] as! String
  let filecreationDate = fileAttribute[FileAttributeKey.creationDate] as! Date

} catch let error {
  print(error.localizedDescription)

【讨论】:

  • 非常有帮助。谢谢。
【解决方案2】:

基于@KarthikeyanBose 的代码:要获取Documents 目录中所有文件的信息,请执行以下操作:

let fileManager = FileManager.default

if let documentsURLs = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
    do {
        let fileNames = try fileManager.contentsOfDirectory(atPath: documentsURLs.path)

        for fileName in fileNames {
            let fileURL = documentsURLs.appendingPathComponent(fileName)

            let fileAttribute = try fileManager.attributesOfItem(atPath: fileURL.path)
            let fileSize = fileAttribute[FileAttributeKey.size] as! Int64
            let fileType = fileAttribute[FileAttributeKey.type] as! String
            let filecreationDate = fileAttribute[FileAttributeKey.creationDate] as! Date
            let fileExtension = fileURL.pathExtension;

            print("Name: \(fileName), Size: \(fileSize), Type: \(fileType), Date: \(filecreationDate), Extension: \(fileExtension)")
        }
    } catch {
        print("Error: \(error)")
    }
} //Handle this "else" error too, even though this really shouldn't happen

此代码打印例如:

Name: Deadpool.png, Size: 39225, Type: NSFileTypeRegular, Date: 2019-05-27 11:03:03 +0000, Extension: png

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 2011-01-11
    • 2018-11-30
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    相关资源
    最近更新 更多