在有效的代码中,我返回的[String]?
包含存储在lastPathComponent
中的文件名(/Documents/
)-按上次修改日期排序。
我相信我可能使用了太多步骤,并且在这里寻找有关如何减少代码的建议。
为了当前获得所需的结果-我正在创建两个中间词典:var attributesDictionary: [String : AnyObject]?
和var urlDictionary = [NSURL:NSDate]()
。循环遍历初始[NSURL]
我正在使用两个步骤-.resourceValuesForKeys
初始化attributesDictionary
。然后,我填充urlDictionary
,使其包含URL和 key NSURLContentModificationDateKey
的值。
我非常确定,应该有一种方法可以实现此结果,而无需创建urlDictionary
和attributesDictionary
且不需要循环。也许直接来自urlArray
。这是我当前的代码:
编辑:不需要Arthur Gevorkyan在第一条评论中指出的do{}
。
func getFileList() -> [String]? {
let directory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let properties = [NSURLLocalizedNameKey, NSURLCreationDateKey, NSURLContentModificationDateKey, NSURLLocalizedTypeDescriptionKey]
// no catch required - contentsOfDirectoryAtURL returns nil if there is an error
if let urlArray = try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: properties, options:NSDirectoryEnumerationOptions.SkipsHiddenFiles) {
var attributesDictionary: [String:AnyObject]?
var dateLastModified: NSDate
var urlDictionary = [NSURL:NSDate]()
for URLs in urlArray {
// no catch required - resourceValuesForKeys returns nil if there is an error
attributesDictionary = try? URLs.resourceValuesForKeys(properties)
dateLastModified = attributesDictionary?[NSURLContentModificationDateKey] as! NSDate
urlDictionary[URLs] = dateLastModified
}
// this approach to sort is used because NSDate cannot be directly compared with </>
return urlDictionary.filter{$0 != nil}.sort{$0.1.compare($1.1) == NSComparisonResult.OrderedDescending }.map{$0.0}.map{$0.lastPathComponent!}
} else {
return nil
}
}
最佳答案
可能的解决方案:
if let urlArray = try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(directory,
includingPropertiesForKeys: properties, options:.SkipsHiddenFiles) {
return urlArray.map { url -> (String, NSTimeInterval) in
var lastModified : AnyObject?
_ = try? url.getResourceValue(&lastModified, forKey: NSURLContentModificationDateKey)
return (url.lastPathComponent!, lastModified?.timeIntervalSinceReferenceDate ?? 0)
}
.sort({ $0.1 > $1.1 }) // sort descending modification dates
.map { $0.0 } // extract file names
} else {
return nil
}
URL数组首先映射到
(lastPathComponent, lastModificationDate)
元组数组,然后根据最后修改日期,最后提取路径名。
可以通过使用
attributesDictionary
来避免getResourceValue(_ : forKey)
仅检索上次修改日期。Swift 3的更新:
let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
if let urlArray = try? FileManager.default.contentsOfDirectory(at: directory,
includingPropertiesForKeys: [.contentModificationDateKey],
options:.skipsHiddenFiles) {
return urlArray.map { url in
(url.lastPathComponent, (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? Date.distantPast)
}
.sorted(by: { $0.1 > $1.1 }) // sort descending modification dates
.map { $0.0 } // extract file names
} else {
return nil
}