Search code examples
swiftmacosnsfilemanager

NSFileManager OS X Last Modify Date


I have two questions on following code:

1) How to get the directory last modified/update date using the NSFileManager as coded below?

2) The array print out only the last record, how to get the result print out in

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

My code as below:

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)")
         }
     }

Solution

  • 1) get the modification date from the URL and compare the dates in the repeat loop.

    2) create an array rather than a dictionary and append the dictionaries.

    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)
        }
    }
    

    The option .SkipsHiddenFiles avoids the check for .DS_Store

    Edit: Updated to Swift 4