Search code examples
iosswiftparse-platformnsattributedstring

How to save attributedstring into Parse server Object type field


I am trying to save an attributed text into Parse server. The field type is Object.

see the code


            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
                }
            }

I am getting this error

schema mismatch for Note.Data; expected Object but got Bytes

Note: the Note.Data column type Object

Any idea how to fix this?

Thanks


Solution

  • The htmlData is a binary data representation of your attributed string. Binary data cannot be directly stored in the database as Parse Server does not support a Parse Object field of type BLOB. You need a representation of the binary data which is compatible with a field type of Parse Server, like the String type.

    You can convert the binary data into a base64 encoded String which is an ASCII representation, simply said, readable text:

    // 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
    

    You'd have to make sure in the Parse Dashboard that the type of your Data column is String.

    However, keep in mind that large data should be stores in Parse Files, as Parse Objects are limited in size to 128 KB. Also, you don't want large data BLOBs in your MongoDB database as it will negatively impact performance when you scale.