Swift 将一些字符串值设置为文件的属性

Swift set some string value to file's attribute

根据Apple的文档,我们可以为一个文件设置很多属性

A dictionary containing as keys the attributes to set for path and as values the corresponding value for the attribute. You can set the following attributes: busy, creationDate, extensionHidden, groupOwnerAccountID, groupOwnerAccountName, hfsCreatorCode, hfsTypeCode, immutable, modificationDate, ownerAccountID, ownerAccountName, posixPermissions. You can change single attributes or any combination of attributes; you need not specify keys for all attributes.

我想为文件设置一个额外的参数。参数是一个字符串,我找不到任何可以设置字符串的属性。 比如我试过

try FileManager.default.setAttributes([FileAttributeKey.ownerAccountName: NSString(string: "0B2TwsHM7lBpSMU1tNXVfSEp0RGs"), FileAttributeKey.creationDate: date], ofItemAtPath: filePath.path)

但是当我加载密钥时

let keys = try FileManager.default.attributesOfItem(atPath: filePath.path)
print(keys)

我只更改了 .creationDate

[__C.FileAttributeKey(_rawValue: NSFileType): NSFileTypeRegular,
__C.FileAttributeKey(_rawValue: NSFilePosixPermissions): 420,
__C.FileAttributeKey(_rawValue: NSFileSystemNumber): 16777220,
__C.FileAttributeKey(_rawValue: NSFileReferenceCount): 1,
__C.FileAttributeKey(_rawValue: NSFileGroupOwnerAccountName): staff,
__C.FileAttributeKey(_rawValue: NSFileSystemFileNumber): 8423614,
__C.FileAttributeKey(_rawValue: NSFileGroupOwnerAccountID): 20,
__C.FileAttributeKey(_rawValue: NSFileModificationDate): 2017-08-16 06:03:57 +0000, 
__C.FileAttributeKey(_rawValue: NSFileCreationDate): 1970-01-01 00:33:20 +0000, 
__C.FileAttributeKey(_rawValue: NSFileSize): 9795,
__C.FileAttributeKey(_rawValue: NSFileExtensionHidden): 0,
__C.FileAttributeKey(_rawValue: NSFileOwnerAccountID): 501]

有什么方法可以将字符串值设置为 FileAttribute?

文档说 "You can set the following attributes"。这意味着您只能通过 API 设置那些特定的属性。

您真正要寻找的是 Extended Attributes,它们使用一组单独的(C 风格)API。

类似于:

let directory = NSTemporaryDirectory()
let someExampleText = "some sample text goes here"
do {
    try someExampleText.write(toFile: "\(directory)/test.txt", atomically: true, encoding: .utf8)
} catch let error {
    print("error while writing is \(error.localizedDescription)")
}
let valueString = "setting some value here"
let result = setxattr("\(directory)/test.txt", "com.Whosebug.test", valueString, valueString.characters.count, 0, 0)

print("result is \(result) ; errno is \(errno)")
if errno != 0
{
    perror("could not save")
}

let sizeOfRetrievedValue = getxattr("\(directory)/test.txt", "com.Whosebug.test", nil, 0, 0, 0)

var data = Data(count: sizeOfRetrievedValue)

let newResult = data.withUnsafeMutableBytes({
    getxattr("\(directory)/test.txt", "com.Whosebug.test", [=10=], data.count, 0, 0)
})

if let resultString = String(data: data, encoding: .utf8)
{
    print("retrieved string is \(resultString)")
}