【发布时间】:2018-01-04 21:25:07
【问题描述】:
我想将一些信息保存到视频元数据中。现在我可以保存文本,即String 对象。
// 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,它崩溃了,现在我坚持将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)?
提前致谢!
【问题讨论】:
标签: swift nsstring nsdata nskeyedarchiver