在没有shell命令的情况下,有没有读取/写入文件标记的方法?已经尝试过NSFileManager和CGImageSource类。到目前为止还没有运气。

发布于 2016-07-28 10:49:10
NSURL对象具有用于密钥NSURLTagNamesKey的资源。该值是一个字符串数组。
这个Swift示例读取标记,添加标记Foo并将标记写回。
let url = NSURL(fileURLWithPath: "/Path/to/file.ext")
var resource : AnyObject?
do {
try url.getResourceValue(&resource, forKey: NSURLTagNamesKey)
var tags : [String]
if resource == nil {
tags = [String]()
} else {
tags = resource as! [String]
}
print(tags)
tags += ["Foo"]
try url.setResourceValue(tags, forKey: NSURLTagNamesKey)
} catch let error as NSError {
print(error)
}Swift的3+版本有点不同。在URL中,tagNames属性是只获取的,因此有必要将URL转换为FoundationNSURL
var url = URL(fileURLWithPath: "/Path/to/file.ext")
do {
let resourceValues = try url.resourceValues(forKeys: [.tagNamesKey])
var tags : [String]
if let tagNames = resourceValues.tagNames {
tags = tagNames
} else {
tags = [String]()
}
tags += ["Foo"]
try (url as NSURL).setResourceValue(tags, forKey: .tagNamesKey)
} catch {
print(error)
}发布于 2017-11-16 23:07:45
@vadian在Swift 4.0中的答案
('NSURLTagNamesKey' has been renamed to 'URLResourceKey.tagNamesKey')
let url = NSURL(fileURLWithPath: "/Path/to/file.ext")
var resource : AnyObject?
do {
try url.getResourceValue(&resource, forKey: URLResourceKey.tagNamesKey)
var tags : [String]
if resource == nil {
tags = [String]()
} else {
tags = resource as! [String]
}
print(tags)
tags += ["Foo"]
try url.setResourceValue(tags, forKey: URLResourceKey.tagNamesKey)
} catch let error as NSError {
print(error)
}https://stackoverflow.com/questions/38633600
复制相似问题