如何使用macosx上的swift从有效的目录路径获取日期修改属性

时间:2016-01-27 05:46:41

标签: macos swift2

我想找到给定有效路径的目录的修改日期。

类似于ls -l -d {path}。

示例:

ls -l -d /Volumes/ARCHIVE/DVD\ 1255
drwxr-xr-x@ 1 fmpserver  staff  1214 26 Nov 11:52 /Volumes/ARCHIVE/DVD 1255

我想我可以使用NSFileManager来获取它。

代码提取:

func setStartDate() {
    let fileManager = NSFileManager.defaultManager() ;
    do {
        let attributes:NSDictionary? = try         fileManager.attributesOfFileSystemForPath(self.rootFolder!) ;    
        print("\(attributes)") ;
        if let _attributes = attributes {
            let attribute = _attributes.fileModificatioDate();
                print( attribute ) ;
        }
    } catch  {
        print("Error: \(error)") ;
    }
}

示例输出:

根据Understanding_Pathnames_in_Swift

应该有一个NSFileModificationDate属性。

当我运行代码时,我得到了

Optional({
    NSFileSystemFreeNodes = 3016781479;
    NSFileSystemFreeSize = 12356736937984;
    NSFileSystemNodes = 4294883316;
    NSFileSystemNumber = 771751939;
    NSFileSystemSize = 17591842070528;
})
nil

显然,因为NSFileModificationDate不是属性字典的一部分。

在macosx上使用swift从有效目录路径获取日期修改属性的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

使用attributesOfItemAtPath而不是attributesOfFileSystemForPath

do {
  let attributes = try NSFileManager.defaultManager().attributesOfItemAtPath(self.rootFolder!)
  let modificationDate = attributes[NSFileModificationDate] as! NSDate
  print(modificationDate)
} catch let error as NSError {
  print(error)
}

或者您也可以使用NSURL

let rootFolderURL = NSURL(fileURLWithPath:self.rootFolder!)
var modificationDate : AnyObject?
do {
  try rootFolderURL.getResourceValue(&modificationDate, forKey: NSURLContentModificationDateKey)
  print(modificationDate as! NSDate)
} catch let error as NSError {
  print(error)
}