2

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

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Anters Bear
  • 1,816
  • 1
  • 15
  • 41

1 Answers1

6

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

Vlad Pulichev
  • 3,162
  • 2
  • 20
  • 34
  • Hey this is helpful, but I think I'm trying to save the data to a file and upload that file to firebase instead. Working on that but having some [issues](https://stackoverflow.com/questions/45040306/saving-struct-as-data-to-file-and-back-again) rn – Anters Bear Jul 11 '17 at 19:02
  • @AntersBear I'm not sure If it is a best practice, but it's your choice. And it can work – Vlad Pulichev Jul 12 '17 at 05:14