Catch
Catch

Reputation: 153

How to write my Struct to Firebase

I have this struct:

struct Info {
    var name: String = ""
    var number = Int()
}

 var infoProvided : [Info] = []    

I display desired data in a tableView:

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell") as! InfoTableViewCell

         let name = infoProvided[indexPath.row].name
         let number = infoProvided[indexPath.row].number

         cell.infoLabelLabel.text = "\(name) with \(number)"

        return cell
    }    

I am trying to write data to firebase like this:

self.ref?.child(gotLokasjon).child(location).child(dateAndTime).updateChildValues(["Signed up:" : infoProvided])

This returns the error:
Cannot store object of type _SwiftValue at 0. Can only store objects of type NSNumber, NSString, NSDictionary, and NSArray.'

How can I write my Struct to Firebase?. I would like to write it equal to how its displayed in the tableView:

 cell.infoLabelLabel.text = "\(name) with \(number)"

Upvotes: 0

Views: 513

Answers (2)

Catch
Catch

Reputation: 153

After a bit of fiddling I did this:

let infoArray = infoProvided.map { [$0.number, $0.name] }
 let items = NSArray(array: infoArray)     

Then implemented that in the above solution. This seams to work.

I don't know if this is a good solution?

Upvotes: 0

Do2
Do2

Reputation: 1791

I haven't understood where you want the upload to happen(before or after they are displayed on tableView) so adjust it to suit your needs.

 guard let name  = infoProvided.name else {return}
 guard let number = infoProvided.number else {return}

 let data = [ "name": name, "number": number] as [String : Any]
 self.ref?.child(gotLokasjon).child(location).child(dateAndTime).updateChildValues(data, withCompletionBlock: { (error, ref) in
                        if error != nil{
                            print(error!)
                            return
                        }
                        print(" Successfully uploaded")
                    })

Upvotes: 1

Related Questions