给文件添加自定义属性

2018-05-27  本文已影响0人  _我和你一样

获取文件属性

let attur = try! FileManager.default.attributesOfItem(atPath: filePath)

文件属性大概如下:


image.png

其中我们要自定义的属性,就需要写在文件扩展属性中。
key是:NSFileExtendedAttributes
但是有两点需要注意:

  1. key 不能直接点出来,在Swift中得这么写:FileAttributeKey.init("NSFileExtendedAttributes")
  2. 对应的值并不是看上去的那样是个字典,它的值是一个Data。
    因此赋值的时候,需要赋值一个Data
    我们可以使用属性列表序列化的方式序列化一个Data
let customInfo = ["isenc":"1","mdataisenc":"0","product_model":"ALX-001"]
let data = try! PropertyListSerialization.data(fromPropertyList:customInfo, format: PropertyListSerialization.PropertyListFormat.binary, options: 0)

然后就可以设置值了

let extendAttribute = [FileAttributeKey.init("NSFileExtendedAttributes"):["customInfo":data]]
do {
    try FileManager.default.setAttributes(extendAttribute, ofItemAtPath: filePath)
} catch  {
    print(error)
}

读取是个反过程:

let attur = try! FileManager.default.attributesOfItem(atPath: helloPath)
let extendedAttribute = attur[FileAttributeKey.init("NSFileExtendedAttributes")] as! NSDictionary
let customData = extendedAttribute["customInfo"] as! Data
var format = PropertyListSerialization.PropertyListFormat.binary
let custom = try PropertyListSerialization.propertyList(from: customData, options: PropertyListSerialization.ReadOptions(rawValue: 0), format: &format)

因为key的值是个data,因此无论如何传个data,是用属性列表序列化,或者json序列化或是其他的都可以,只要转成data就好,读取和写入是个相关的过程,序列化要保持一致。

上一篇 下一篇

猜你喜欢

热点阅读