简体   繁体   中英

Getting Invalid Firebase Data error when trying to save to Firebase using Swift

Objective: Save Drinks order to Firebase

Problem: Converting [Drink] array to Dictionary

I get the following error message:

ERROR: 'InvalidFirebaseData', reason: '(setValue:withCompletionBlock:) Cannot store object of type vipeeps.Drink at drinksOrdered.0009373. Can only store objects of type NSNumber, NSString, NSDictionary, and NSArray.'

func saveDrinkOrder(orderRef: String, venueName: String, drinksOrder: [Drink], chargeId: String, chargeObject: [String: Any], handler: @escaping(Bool) -> ()){

        guard let uid = Auth.auth().currentUser?.uid else { return }

        let orderNo = orderRef

        let timeStamp = Date().timeIntervalSince1970

        let drinksOrdered = Dictionary(uniqueKeysWithValues: drinksOrder.map {($0.posId, $0.self)}) //<---issue here: $0.self if still a Drink object

        let venue = venueName

        let stripeChargeResponse = chargeObject

        let ref = REF_DRINK_ORDERS.child(uid).child(orderNo)


        //message node values
        let values = [
            "dateOrdered": timeStamp,
            "venueName": venue,
            "timeStamp": Date().timeIntervalSince1970,
            "drinksOrdered": drinksOrdered,
            "stripeResponse": stripeChargeResponse] as [String : Any]

        ref.setValue(values) { (error, dbRef) in

            if error != nil {
                print(error!.localizedDescription)
                handler(false)
                return
            }

            handler(true)

        }//end setValue

    }//end func

asdf

class Drink {

    var posId: String?
    var name: String?
    var description: String?
    var tags: [String]?
    var unitPrice: String?

    init(dictionary: [String: Any]) {

        self.posId = dictionary["posId"] as? String
        self.name = dictionary["name"] as? String
        self.description = dictionary["description"] as? String
        self.unitPrice = dictionary["unitPrice"] as? String
        self.tags = dictionary["tags"] as? [String]


    }//end init

}//end class

I figured it out, probably not the most efficient approach but it works:

  1. I updated my Drink class to return the object as a Dictionary[String:Any]

    var asDictionary : [String:Any] { let mirror = Mirror(reflecting: self) let dict = Dictionary(uniqueKeysWithValues: mirror.children.lazy.map({ (label:String?, value:Any) -> (String, Any)? in guard let label = label else { return nil } return (label, value) }).compactMap { $0 }) return dict }

  2. Loop through the [Drinks] array to create a Dictionary to Firebase

    var drinksDict = String:Any

     for drink in drinksOrder { drinksDict[drink.posId!] = drink.asDictionary

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM