问题与查询Firebase - Swift
问题描述:
我目前正在尝试执行查询以获取显示关注者/关注列表的信息。我目前得到一个错误这样:Could not cast value of type 'FIRDataSnapshot' (0x108967580) to 'NSArray' (0x10b3e3e28).
我是新来的火力和仍在学习的查询,我的查询如下:问题与查询Firebase - Swift
if isFollowers == true {
self.isFollowers = true
ref = ref.child("followers")
let query = ref.queryOrdered(byChild: "userFollow")
query.queryLimited(toLast: 5).observeSingleEvent(of: .value, with: { (snapshot : FIRDataSnapshot) in
if snapshot.childrenCount > 0 {
for s in snapshot.children.allObjects.first as! [FIRDataSnapshot] {
print("are we even in here?")
let item = s.value as! Dictionary<String,AnyObject?>
let user = FollowInfoForUser(dictionary: item as Dictionary<String,AnyObject>)
self.userFollowIndex.insert(user, at: 0)
print(self.userFollowIndex)
//print(self.userFollowIndex.count)
self.collectionView.reloadData()
}
} else {
print("sorry no followers for you to see")
}
})
}
错误的路线是这样的:
for s in snapshot.children.allObjects.first as! [FIRDataSnapshot] {
我树也如下:
-Users
---UserUID
-----Followers
--------FollowAutoChild
----------------userFollow
----------------userFollowKey
我试图存储FollowAutoChild信息
我的整个查询功能代码如下:
func setValues(isFollowers : Bool, isFollowing : Bool, isViewingSelf : Bool, isViewingOther : Bool, key : String) {
var ref = FIRDatabase.database().reference().child("users")
if isViewingSelf {
print("we are viewing us")
ref = ref.child(FIRAuth.auth()!.currentUser!.uid)
} else
if isViewingOther {
print("we are viewing them")
ref = ref.child(key)
}
if isFollowers == true {
self.isFollowers = true
ref = ref.child("followers")
let query = ref.queryOrdered(byChild: "userFollow")
query.queryLimited(toLast: 5).observeSingleEvent(of: .value, with: { (snapshot : FIRDataSnapshot) in
if snapshot.childrenCount > 0 {
for s in snapshot.children.allObjects.first as! [FIRDataSnapshot] {
print("are we even in here?")
let item = s.value as! Dictionary<String,AnyObject?>
let user = FollowInfoForUser(dictionary: item as Dictionary<String,AnyObject>)
self.userFollowIndex.insert(user, at: 0)
print(self.userFollowIndex)
//print(self.userFollowIndex.count)
self.collectionView.reloadData()
}
} else {
print("sorry no followers for you to see")
}
})
}
}
答
的误差出现,因为你是铸造的snapshot.children
的第一元件,这仅仅是一个元件(在这种情况下的FIRDataSnapshot
),作为阵列FIRDataSnapshot
的。或者将所有对象作为FIRDatasnapShot
的数组,或作为FIRDataSnapshot
的第一个数组投射,但不能同时投射。
答
你for_in循环应该是这样的
for s in snapshot.children.allObjects as! [FIRDataSnapshot] {
print("are we even in here?")
let item = s.value as! [String: AnyObjcet]
let user = FollowInfoForUser(dictionary: item)
self.userFollowIndex.insert(user, at: 0)
print(self.userFollowIndex)
//print(self.userFollowIndex.count)
self.collectionView.reloadData()
}
你做错了铸造
的误差出现,因为你是铸造** **第一'snapshot.children'的元素,它只是一个元素(在这种情况下是一个'FIRDataSnapshot'),作为'FIRDataSnapshot'的数组。既可以将所有对象作为“FIRDatasnapShot”的数组进行投射,也可以将第一个对象作为FIRDataSnapshot进行投射,但不能同时投射。 – Eric
非常感谢!我不知道! – AndrewS
很高兴能有帮助:) – Eric