gpt4 book ai didi

swift - NSFileManager OS X 最后修改日期

转载 作者:搜寻专家 更新时间:2023-11-01 07:27:16 26 4
gpt4 key购买 nike

我对以下代码有两个问题:

1) 如何使用如下编码的 NSFileManager 获取目录的最后修改/更新日期?

2) 数组只打印最后一条记录,如何得到结果打印在

[
["ProjectName":"Project 1", "ProjectURL":"/Users/abc/Documents/MyProjectFolder/Project 1"],
["ProjectName":"Project 2", "ProjectURL":"/Users/abc/Documents/MyProjectFolder/Project 2"]
]

我的代码如下:

let documentsDirectoryURL =  try! NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)

var bool: ObjCBool = false

myPath = NSURL(string: String(documentsDirectoryURL) + "MyProjectFolder")
var filevar: [String:String] = [:]
if NSFileManager().fileExistsAtPath(myPath.path!, isDirectory: &bool) {
if bool.boolValue {
let fileManager = NSFileManager.defaultManager()
let files = try! fileManager.contentsOfDirectoryAtURL(myPath, includingPropertiesForKeys: nil, options: [])
for file in files {
let filename = file.lastPathComponent
let fileurl = file.path
if filename != ".DS_Store"{
filevar = ["ProjectName":filename!, "ProjectURL": fileurl!]
}
}
print("Result:\n \(filevar)")
}
}

最佳答案

1) 从 URL 中获取修改日期并比较重复循环中的日期。

2) 创建一个数组而不是字典并附加字典。

let fileManager = FileManager.default
let documentsDirectoryURL = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

var isDir: ObjCBool = false

let myPath = documentsDirectoryURL.appendingPathComponent("MyProjectFolder")
var filevar = [[String:String]]()

var latestModificationDate = Date.distantPast
var latestFileURL = URL(fileURLWithPath: "/")
if fileManager.fileExists(atPath: myPath.path, isDirectory: &isDir) {
if isDir.boolValue {
do {
let fileURLs = try fileManager.contentsOfDirectory(at: myPath, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for fileURL in fileURLs {
let attributes = try! fileURL.resourceValues(forKeys:[.contentModificationDateKey, .nameKey])
let filename = attributes.name!
let modificationDate = attributes.contentModificationDate!
if latestModificationDate.compare(modificationDate) == .orderedAscending {
latestModificationDate = modificationDate
latestFileURL = fileURL
}
filevar.append ( ["ProjectName":filename, "ProjectURL": fileURL.path])
}
} catch {
print(error)
}
print("Result:\n \(filevar)")
print(latestFileURL, latestModificationDate)
}
}

选项 .SkipsHiddenFiles 避免检查 .DS_Store

编辑:更新到 Swift 4

关于swift - NSFileManager OS X 最后修改日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35179676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com