Anters Bear
Anters Bear

Reputation: 1956

Saving a complex struct to firebase

I have some really complex structs that are made up of custom UIViews and other swift object. I would like to save instances of them on Firebase. The problem is Firebase won't accept my types, so I could write code to convert to more primitive types and back, but this will be extremely complicated and tedious. I was wondering if there is some way for me to save an entire class as data, binary, or a string upload it and retrieve and decode it later? Or any other suggestions

Upvotes: 2

Views: 1516

Answers (1)

Vlad Pulichev
Vlad Pulichev

Reputation: 3272

From documentation:

You can pass set a string, number, boolean, null, array or any JSON object

So, you need to write your own converters.

Just create structs/classes for objects with 3 methods:

// example with 2 fields: Int and String

struct ItemFromFirebase {
    let type: Int
    let name: String

    // manual init
    init(type: Int, name: String) {
       self.type = type
       self.name = name
    }

    // init with snapshot
    init(snapshot: DataSnapshot) {
         let snapshotValue = snapshot.value as! [String: AnyObject]
         type = snapshotValue["type"] as! Int
         name = snapshotValue["name"] as! String
    }

    // function for saving data
    func toAnyObject() -> Any {
        return [
            "type": type,
            "name": name
        ]
     }
 }

It's example with simple types. You just need to rewrite functions toAnyObject and init to your needs.

Hope it helps

Upvotes: 6

Related Questions