首页 > 解决方案 > 如何将属性字符串保存到解析服务器对象类型字段中

问题描述

我正在尝试将属性文本保存到 Parse 服务器中。字段类型为对象。

看代码


            let htmlData = try attributedText
                .data(from: NSRange(location: 0,
                                    length: attributedText.length),
                      documentAttributes: documentAttributes)
            // htmlData is Data type
            let note = PFObject(className:"Note")
            note["Data"] = htmlData
            note.saveEventually { (success, error) in
                if (success) {
                    // success is false
                }
            }

我收到此错误

Note.Data 的架构不匹配;预期对象但得到字节

注意:Note.Data列类型Object

知道如何解决这个问题吗?

谢谢

标签: iosswiftparse-platformnsattributedstring

解决方案


htmlData是属性字符串的二进制数据表示。二进制数据不能直接存储在数据库中,因为 Parse Server 不支持BLOB类型的 Parse Object 字段。您需要与 Parse Server 的字段类型兼容的二进制数据的表示,例如String类型。

您可以将二进制数据转换为base64编码String,这是一种 ASCII 表示,简单地说,可读文本:

// Create binary data from attributed text
let htmlData = try attributedText.data(
    from: NSRange(location: 0, length: attributedText.length),
    documentAttributes: documentAttributes)

// Create string from binary data
let base64HtmlData = htmlData.base64EncodedData(options:[])

// Store string in Parse Object field of type `String`
let note = PFObject(className: "Note")
note["Data"] = base64HtmlData

您必须确保在 Parse Dashboard 中Data列的类型是String.

但是,请记住,大数据应该存储在 Parse Files 中,因为 Parse Objects 的大小限制为128 KB。此外,您不希望 MongoDB 数据库中存在大数据 BLOB,因为它会在您扩展时对性能产生负面影响。


推荐阅读