使用Firebase更新数据模型

时间:2020-10-02 12:12:56

标签: ios swift firebase firebase-realtime-database swiftui

关于View负载,我想根据Firebase实时数据库更新ImageDataModel的收藏夹值。

//ImageDataModel.swift

struct ImageDataModel {
    var image: String
    var title: String
    var favorite: String
}

extension ImageDataModel {
    static var data: [ImageDataModel] = [
        ImageDataModel(image: "image_1", title: "XXXXX", favorite: "N"),
        ImageDataModel(image: "image_2", title: "YYYYY", favorite: "N"),
        ImageDataModel(image: "image_3", title: "ZZZZZ", favorite: "N")
    ]
}

初始视图

struct ImageStepView: View {

var data: ImageDataModel
var ref: DatabaseReference = Database.database().reference()
var userID = UIDevice.current.identifierForVendor!.uuidString

var body: some View {
    
    VStack{
        ...
    }.onAppear { self.getFavoriteImages() }
}

func getFavoriteImages(){
    
    ref.child("users").child(userID).observeSingleEvent(of: .value, with: { (snapshot) in
        let value = snapshot.value as? NSDictionary
        print("value::",value ?? "") // value:: {"image_1" = "Y"; "image_3" = "Y";}

        //Here I want to update the ImageDataModel 
        
    }) { (error) in
        print(error.localizedDescription)
    }
  }
}

例如,如果Firebase返回的值包含{"image_1" = "Y"; "image_3" = "Y";},而不是我想要像这样更新我的ImageDataModel

extension ImageDataModel {
        static var data: [ImageDataModel] = [
            ImageDataModel(image: "image_1", title: "XXXXX", favorite: "Y"),
            ImageDataModel(image: "image_2", title: "YYYYY", favorite: "N"),
            ImageDataModel(image: "image_3", title: "ZZZZZ", favorite: "Y")
        ]
    }

// Firebase数据结构示例

{
  "A9E41390-7557-4FE3-A319-B4472048AF94" : {
    "image_1" : "Y",
    "image_3" : "Y"
  }
}

我不确定这是否是最好的方法,但我将非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

似乎您在每个用户ID下都有一个子节点列表。在这种情况下,您需要在snapshot.children上循环以将每个子节点作为DataSnapshot

ref.child("users").child(userID).observeSingleEvent(of: .value, with: { (snapshot) in
    for child in snapshot.children.allObjects as! [DataSnapshot] {
        let childKey = child.key
        let childValue = child.value as! String

        let model = ImageDataModel(image: childKey, title: "???", favorite: childValue)

        ...
    }
}) { (error) in
    print(error.localizedDescription)
}