简体   繁体   English

如何从Firebase快照设置变量(Swift)

[英]How to set variables from a Firebase snapshot (swift)

I would like to grab the data from my Firebase snapshot and set it to variables in my Project. 我想从Firebase快照中获取数据并将其设置为Project中的变量。 I get the data, but I don't know how to parse it so I can set them. 我得到了数据,但是我不知道如何解析它,所以我可以对其进行设置。 I'm trying to do something like what SwiftyJSON does with API calls. 我正在尝试做类似SwiftyJSON对API调用的操作。

Here is my data structure in firebase: 这是我在firebase中的数据结构: 数据结构

Here is my function: 这是我的功能: 功能

Here is the output in the console: 这是控制台中的输出: 产量

Is there any way to parse and set values from the (ls) array and set the "fromId", "text", "toId" to different variables for each node? 有什么方法可以解析和设置(ls)数组中的值,并将每个节点的“ fromId”,“ text”,“ toId”设置为不同的变量?

Try using:- 尝试使用:-

FIRDatabase.database().reference().child("users/userID/ls").observeSingleEvent(of : .value, with : {(Snap) in 

  if let snapDict = Snap.value as? [String:AnyObject]{

      for each in snapDict{

           print("\(each.value["fromId"] as! String)")

         }
   }
})

您应该能够将FIRDataSnapshot值转换为[String:Any]字典,然后使用“ fromId”,“ text”和“ toId”键访问这些值并将这些值分配给变量。

The easy way would be: SnapshotParser 最简单的方法是: SnapshotParser

Just implement your classes: 只需实现您的类:

func main(){
    let users=SnapshotParser().parseAsList(snap: Snapshot, type: User.self)
    for user in users{
        //do something with your object
    }
}

class User: ParsableSnapshot {
    var id:String?=nil
    var email:String?=nil
    var ls:[Ls]?=nil

    required init(){}

    func bindProperties(binder: SnapshotParser.Binder) {
        binder.bindField(name: "id", field: &id)
        binder.bindField(name: "email", field: &email)
        binder.bindList(name: "ls", list: &ls)
    }
}

class Ls: ParsableSnapshot {
    var id:String?=nil
    var fromId:String?=nil
    var text:String?=nil
    var told:String?=nil

    required init(){}

    func bindProperties(binder: SnapshotParser.Binder) {
        binder.bindField(name: "id", field: &id)
        binder.bindField(name: "fromId", field: &fromId)
        binder.bindField(name: "text", field: &text)
        binder.bindField(name: "told", field: &told)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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