Getting all available folder metadata on OS X using swift

半腔热情 提交于 2019-12-11 09:56:11

问题


I'm writing a swift program, and I want to list all metadata of a given folder using swift. As I understand, I'll need NSMetadataItem. The reference doc of NSMetadataItem is not very clear to me though, so I'm unable to write a code sample here. How to list all metadata of a folder?


回答1:


Initialize a new instance of NSMetadataItem with the folder's NSURL:

let item = NSMetadataItem(URL: folderURL)

Then safely unwrap the values:

if let item = item,
        attributes = item.valuesForAttributes(item.attributes) {
    print(attributes)
}

Here attributes is a [String : AnyObject] dictionary of the folder metadata attributes, like:

["_kTimeMachineIsCreationMarker": 1, "kMDItemFSCreationDate": 2015-03-09 11:49:57 +0000, "_kTimeMachineOldestSnapshot": 2016-01-29 14:50:21 +0000, "kMDItemFSNodeCount": 4, "kMDItemFSTypeCode": 0, "kMDItemFSLabel": 0, "kMDItemFSContentChangeDate": 2015-05-05 15:24:42 +0000, "kMDItemFSOwnerGroupID": 20, "kMDItemFSFinderFlags": 0, "kMDItemFSName": Shared Playground Data, "kMDItemContentCreationDate": 2015-03-09 11:49:57 +0000, "kMDItemKind": Dossier, "kMDItemFSIsExtensionHidden": 0, "_kTimeMachineNewestSnapshot": 4001-01-01 00:00:00 +0000, "kMDItemFSOwnerUserID": 501, "kMDItemFSInvisible": 0, "kMDItemContentTypeTree": <__NSArrayI 0x7f9fdbc05b70>( public.folder, public.directory, public.item ) , "kMDItemContentModificationDate": 2015-05-05 15:24:42 +0000, "kMDItemContentType": public.folder, "kMDItemDateAdded": 2015-03-09 11:49:57 +0000, "kMDItemDisplayName": Shared Playground Data, "kMDItemFSCreatorCode": 0]




回答2:


You can extend NSURL to get all metadata from your url as follow:

extension NSURL {
    var metadataItemAttributes: [String]? {
        return  NSMetadataItem(URL: self)?.attributes
    }
    var creationDateValue: NSDate? {
        return  NSMetadataItem(URL: self)?.valueForAttribute(NSMetadataItemFSCreationDateKey) as? NSDate
    }
    var modifiedDateValue: NSDate? {
        return  NSMetadataItem(URL: self)?.valueForAttribute(NSMetadataItemFSContentChangeDateKey) as? NSDate
    }
    var nameValue: String? {
        return  NSMetadataItem(URL: self)?.valueForAttribute(NSMetadataItemFSNameKey) as? String
    }
    var displayNameValue: String? {
        return  NSMetadataItem(URL: self)?.valueForAttribute(NSMetadataItemDisplayNameKey) as? String
    }
    var fileSizeValue: Int? {
        return  (NSMetadataItem(URL: self)?.valueForAttribute(NSMetadataItemFSSizeKey) as? NSNumber)?.integerValue
    }
}

Testing:

let desktopURL = NSFileManager.defaultManager().URLsForDirectory(.DesktopDirectory, inDomains: .UserDomainMask).first!

print(desktopURL.creationDateValue)


来源:https://stackoverflow.com/questions/35350543/getting-all-available-folder-metadata-on-os-x-using-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!