简体   繁体   English

来自目录文件夹的文件日期

[英]Files date from directory folder

How could I get the date from each file in the directory ?如何从目录中的每个文件中获取日期?

let directoryContent = try fileManager.contentsOfDirectory(atPath: directoryURL.path)

That's how i get files from directory.这就是我从目录中获取文件的方式。 I found a few methods :我找到了几种方法:

directoryContent.Contains(...)

The file where data is older then few days - how could i check it ?数据较旧几天的文件 - 我如何检查它?

then;然后;

let fileAttributes = try fileManager.attributesOfItem(atPath: directoryURL.path)

It is going to give me last file in the directory.它会给我目录中的最后一个文件。

And this going to return date in bytes :这将以字节为单位返回日期:

for var i in 0..<directoryContent.count {
                let date = directoryContent.index(after: i).description.data(using: String.Encoding.utf8)!
                print(date)
            }

Which one is the best way to recive the date from all files or check if the directory conteins specific dates which are older then X time.哪一种是从所有文件中获取日期或检查目录是否包含比 X 时间早的特定日期的最佳方法。

Thanks in advance!提前致谢!

It's highly recommended to use the URL related API of FileManager to get the file attributes in a very efficient way.强烈建议使用FileManagerURL相关 API 以非常有效的方式获取文件属性。

This code prints all URLs of the specified directory with a creation date older than a week ago.此代码打印创建日期早于一周前的指定目录的所有 URL。

let calendar = Calendar.current
let aWeekAgo = calendar.date(byAdding: .day, value: -7, to: Date())!

do {
    let directoryContent = try fileManager.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: [.creationDateKey], options: .skipsHiddenFiles)
    for url in directoryContent {
        let resources = try url.resourceValues(forKeys: [.creationDateKey])
        let creationDate = resources.creationDate!
        if creationDate < aWeekAgo {
            print(url)
            // do somthing with the found files
        }
    }
}
catch {
    print(error)
}

If you want finer control of the workflow for example an URL is invalid and you want to print the bad URL and the associated error but continue precessing the other URLs use an enumerator, the syntax is quite similar:如果您想要更好地控制工作流,例如 URL 无效,并且您想要打印错误的 URL 和相关的错误,但继续使用枚举器处理其他 URL,则语法非常相似:

do {
    let enumerator = fileManager.enumerator(at: directoryURL, includingPropertiesForKeys: [.creationDateKey], options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles], errorHandler: { (url, error) -> Bool in
        print("An error \(error) occurred at \(url)")
        return true
    })
    while let url = enumerator?.nextObject() as? URL {
        let resources = try url.resourceValues(forKeys: [.creationDateKey])
        let creationDate = resources.creationDate!
        if creationDate < last7Days {
            print(url)
            // do somthing with the found files
        }
    }
    
}
catch {
    print(error)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM