有几种方法可以做到这一点。首先看我对这个问题的回答将属性字符串保存到 Firestore https://stackoverflow.com/questions/61981000/can-you-save-attributed-strings-to-cloud-firestore/62008574#62008574在 Firestore 中查看它的完成情况。
这个答案适用于实时数据库,但概念是相似的。
将属性字符串从 textView 转换为 NSData,然后将其作为字符串存储在 Firebase 中。
Firebase 支持 NSString(Swift 中的 String),但仅支持实际的 UTF-8 字符,而不支持格式和样式。
因此,关键是将 textView 中的文本捕获为属性字符串,将其存档为 NSData(数据),然后将其文本版本(base64Encoded)保存在 Firebase 中。然后在回读时,做相反的事情。
以下是如何在 Firebase 中存储来自 sourceTextView 的文本
func saveAttrStringToFirebase() {
let attrString = self.sourceTextView.attributedString()
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: attrString, requiringSecureCoding: false)
let dataString = data.base64EncodedString()
let ref = self.ref.child("attributed_string") //self.ref points to my Firebase
ref.setValue(dataString)
} catch let err as NSError {
print(err.localizedDescription)
}
}
那么 Firebase 将看起来像这样
root
attributed_string: "YnBsaXN0MDDUAQIDB..."
然后读回 attribute_string 处的值,它只是一个字符串。然后将其投射回数据并最后取消存档
func getAttrStringFromFirebase() {
let ref = self.ref.child("attributed_string")
ref.observeSingleEvent(of: .value, with: { snapshot in
if let dataString = snapshot.value as? String {
do {
guard let data = Data(base64Encoded: dataString) else { return }
guard let attrString = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSAttributedString.self, from: data) else { return }
self.destinationTextView.textStorage?.append(attrString)
} catch let err as NSError {
print(err.localizedDescription)
}
}
})
}