【发布时间】:2018-10-10 14:38:42
【问题描述】:
我有以下函数从 Firebase 获取数据,填充 compliments 数组,并假设通过完成 handler 将数组传回。
即使添加了对象,返回的数组也总是空的?
我是否将完成处理程序代码放置在错误的位置,我尝试在所有花括号内插入,但没有任何效果。
handler(compliments, true) 执行行的断点输出如下:
0x0000000102bb3fe8 vipeeps`partial apply forwarder for closure #1 (Swift.Array<Any>, Swift.Bool) -> () in vipeeps.ConversationsListVC.loadNewInvitesData() -> () at ConversationsListVC.swift
功能:
func getComplimentsReceived(forUserId forId: String, handler: @escaping (_ complimentPack: [[String : Any]] ,_ success: Bool) -> ()){
var compliments = [[String : Any]]()//empty array to hold compliments
REF_USERS_COMPLIMENTS.child(forId).observe(.value) { (snapshot) in
for item in snapshot.children{
let itemSnap = item as! DataSnapshot
let dict = itemSnap.value as! [String : Bool]
for (key, status) in dict {
switch status {
case true:
//print(status)
self.REF_USERS.child(snapshot.key).observeSingleEvent(of: .value, with: { (snapshot) in
let uid = snapshot.key
let name = snapshot.childSnapshot(forPath: "name").value as! String
let email = snapshot.childSnapshot(forPath: "email").value as! String
let profilePictureURL = snapshot.childSnapshot(forPath: "profilePictureURL").value as! String
let birthday = snapshot.childSnapshot(forPath: "birthday").value as! String
let firstName = snapshot.childSnapshot(forPath: "firstName").value as! String
let lastName = snapshot.childSnapshot(forPath: "lastName").value as! String
let gender = snapshot.childSnapshot(forPath: "gender").value as! String
let discoverable = snapshot.childSnapshot(forPath: "discoverable").value as! Bool
let online = snapshot.childSnapshot(forPath: "online").value as! Bool
let discoveryPrefs = snapshot.childSnapshot(forPath: "discoveryPrefs").value as! [String : Any]
let dictionary: [String : Any] = ["uid": uid, "name": name, "email": email, "profilePictureURL": profilePictureURL, "birthday": birthday, "firstName": firstName, "lastName": lastName, "gender": gender, "discoverable": discoverable, "online": online, "discoveryPrefs": discoveryPrefs]
let user = User(uid: uid, dictionary: dictionary)
let complimentPack = [
"type": "compliment",
"complimentId": key,
"active": status,
"fromUser": user
] as [String : Any]
compliments.append(complimentPack)
print("compliments.count: \(compliments.count)")
})//end observer
case false:
print(status)
break
}//end switch
}//end for dict
}//end for snapshot.item
handler(compliments, true)
}//end observe
}//end func
数据结构:
【问题讨论】:
-
这段代码无论如何都不会按预期工作,因为您在调用内部(异步)闭包之前调用了最后的
handler(..)语句。顺便说一句:为什么您将compliments和数组参数声明为未指定的[Any],尽管您清楚地知道这是更指定的[[String:Any]]? Swift 3+ 的闭包语法是@escaping ([Any] , Bool) -> ()没有下划线和参数标签。 -
从 'end observe' 范围内调用处理程序,而不是在 'end for snapshot.item' 范围内并尝试!
-
谢谢@vadian 我已经做出了你建议的改变。
-
谢谢@vivekDas 试过了,但还是没有运气:(我用最新的代码编辑了我的问题。
-
observeSingleEvent异步工作。循环立即执行,handler(..)在第一个闭包通过其snapshot之前被调用很长时间(就计算机速度而言)。