将Firebase数据附加到Swift中的数组 [英] Append Firebase data to an array in Swift

查看:146
本文介绍了将Firebase数据附加到Swift中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道我做错了什么!我只是想从Firebase数据库获取数据,并对每个结果进行迭代并将其放入数组中。我尝试了不同的方法。但是他们都返回一次一个结果到数组的结果。结果如下所示:

  [1] 
[1,2]
[1,2,3]
[1,2,3,4]
/ pre>

你可以看到它每次迭代都会添加一个对象。
这里是我所拥有的:

$ $ p $ {code> let ref = FIRDatabase.database()。reference()。child(用户)
ref.observeEventType(.ChildAdded,withBlock:{snapshot in
userUrl = snapshot.value?[profile_image_1] as!String
imageArray.insert(userUrl,atIndex:0 )
},withCancelBlock:{
print(error.description)
})

我也试过这个:
$ b $ pre $ let userUrl =(snapshot.value.objectForKey(profile_image_1 ))as!字符串
imageArray.append(userUrl)

我只是想把每个结果放入一个数组

  [1,2,3)我可以一次访问数据, ,4] 

任何帮助都会很棒!

数据库:
Firebase数据库结构

解决方案

尝试这样的事情:

<$ p $()code $ var $ image $ {

func appendData(){
let ref = FIRDatabase.database()。reference()。child(users)
$ b ref.observeEventType(.Value,withBlock:{snapshot in
var tempImageArray = []

用于snapshot.children中的用户{
userUrl = user.value?[profile_image_1] as?String
self.imageArray.insert(userUrl,atIndex:0)
tempImageArray.append(broadcastItem)
}

self.imageArray = tempImageArray
))
}

edit:I updated代码,请试试这个。

I don't know what I am doing wrong! I just simply want to take data from Firebase database and iterate for each result and put them into an array. I have tried serval different approaches. But they all return results adding one at a time to the array. Resulting in an array looking like this:

["1"]
["1","2"]
["1","2","3"]
["1","2","3","4"]

as you can see it adds one object each time it iterates. Here is what I have:

let ref = FIRDatabase.database().reference().child("users")
ref.observeEventType(.ChildAdded, withBlock: { snapshot in
    userUrl = snapshot.value?["profile_image_1"] as! String
    imageArray.insert(userUrl, atIndex: 0)
}, withCancelBlock: { error in
    print(error.description)
}) 

and I have also tried this:

let userUrl = (snapshot.value.objectForKey("profile_image_1")) as! String
imageArray.append(userUrl)

I just want to put each result into an array I can access the data at once, outside of the completion block.

["1","2","3","4"]

Any help would be great!

Database: Firebase Database Structure

解决方案

Try something like this:

var imageArray = []

func appendData(){
    let ref = FIRDatabase.database().reference().child("users") 

    ref.observeEventType(.Value, withBlock: { snapshot in
        var tempImageArray = []

        for user in snapshot.children {
            userUrl = user.value?["profile_image_1"] as? String
            self.imageArray.insert(userUrl, atIndex: 0)
            tempImageArray.append(broadcastItem)
        }

        self.imageArray = tempImageArray
    })
}

edit: I updated the code, please try this.

这篇关于将Firebase数据附加到Swift中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆