我想将一些信息保存到视频元数据中。现在我可以保存文本,即String
对象。是否可以将NSData(从NSKeyedArchiver获得)作为NSString保存,然后作为NSData读回?
// this works well
let metaItem = AVMutableMetadataItem()
metaItem.key = AVMetadataCommonKeySource as NSCopying & NSObjectProtocol
metaItem.keySpace = AVMetadataKeySpaceCommon
metaItem.value = String("some text") as! NSCopying & NSObjectProtocol
因此,而不是只是String
我想序列化的自定义对象:
class ARTRMetadata: NSObject, NSCoding {
// ...
required init(coder aDecoder: NSCoder) {
//...
}
func encode(with aCoder: NSCoder) {
//...
}
}
我试图Data
转换为String
,它坠毁,现在我stucked在写入/读取Data
到.txt
文件:
static func saveMetadataObjectAsText(memento: ARTRMetadata)->String {
let tempFilepath = NSTemporaryDirectory().appending("someFile2.txt")
FileManager.default.createFile(atPath: tempFilepath, contents: nil, attributes: nil)
if NSKeyedArchiver.archiveRootObject(memento, toFile: tempFilepath) {}
else { print("archiveRootObject toFile: FAILURE") }
do {
let contentsFeedToMetadataItem = try String(contentsOfFile: tempFilepath)
//let contentsFeedToMetadataItem = try String(contentsOfFile: tempFilepath, encoding: String.Encoding.utf8) // The file “someFile2.txt” couldn’t be opened using text encoding Unicode (UTF-8).
return contentsFeedToMetadataItem
}
catch { print(error) }
return "ERROR in contentsFeedToMetadataItem"
}
现在它崩溃,因为“文件”someFile2.txt“无法打开因为其内容的文本编码无法确定。“
我想问题是从NSKeyedArchiver
获得的NSData
无效NSString
。如果我是正确的,如何将数据转储为文本?然后用相同的字节恢复它(对于NSKeyedUnarchiver
)?
提前致谢!
非常感谢!我会在星期一检查它,然后会接受。 :) –