swiftuikitrealmuitextviewmongodb-realm

I want to store formatted text in Realm Swift database


noob swift guy here. I have this UITextView where the user writes something. I need to store his "note" to the database with all the formated text in it. That means if it has bold, I need to display it as bold later. This text should be stored in local Realm Swift Database. Any solutions how can I achieve that? I head about "Markdown", but I didn't understand how can that be useful.

Much thanks! Have a great day!


Solution

  • Realm only stores ascii text and cannot directly store any formatting properties like BOLD, and that's true for most databases.

    If you want to store formatted strings, one option is to archive it to a Data type, which Realm fully supports. Then, when reading data back in, unarchive it from Data back to a formatted string. (formatted strings are often called Rich Text or in code: attributedStrings)

    The below code is macOS but iOS will be similar

    A quick example - here's a class to hold a some attributed string data

    class MyAttrStringClass: Object {
       @Persisted var attrStringData: Data!
    }
    

    Suppose we have a (rich) text field with the following text

    Hello, World

    To store the class with the attributed string in Realm:

    let s = self.myRichTextField.attributedStringValue
    let data = try! NSKeyedArchiver.archivedData(withRootObject: s, requiringSecureCoding: false)
    
    let myObject = MyAttrStringClass()
    myObject.attrStringData = data
    
    try! realm.write {
        realm.add(myObject)
    }
    

    then when reading back from Realm and displaying the attributed string in that same field

    let myObject = realm.objects(MyAttrStringClass.self).first!
    
    let data = myObject.attrStringData!
    let s = try! NSKeyedUnarchiver.unarchivedObject(ofClass: NSAttributedString.self, from: data)
    
    self.myRichTextField.attributedStringValue = s!
    

    Note: there's no error checking in the above. Please protect your code by safely unwrapping optionals.