我正在我的应用程序上创建一个 friend 列表,fetchfriends 列出了这个人是 friend 的用户,获取用户然后查看这个列表并用 friend 信息填充一个 TableView 。这似乎可以正常工作,但由于某种原因,在获取 friend 之前正在运行获取用户,有人可以帮我解决这个问题吗?这是我的代码。我什至尝试了一个条件语句,它现在被注释掉了,但它从来没有以这种方式运行第二个函数。
override func viewDidLoad() {
super.viewDidLoad()
ref = FIRDatabase.database().reference()
friendsTableView.delegate = self
friendsTableView.dataSource = self
fetchfriends()
//if userspresent == true {
fetchuser()
// }
// Do any additional setup after loading the view.
}
func fetchfriends () {
ref.child("users").child(userID!).child("friends").observeSingleEvent(of: .value, with: { (snapshot) in
if let value = snapshot.value as? NSDictionary {
let userName = value["username"] as? String ?? ""
let friendid = value["userid"] as? String ?? ""
self.userIds.append(friendid)
self.userspresent = true
print(userName, friendid)
}
})
}
// var index1:Int = 0
//if userspresent == true {
func fetchuser () {
//let count = userIds.count
for index1 in 0...userIds.count-1 {
ref.child("users").child(userIds[index1]).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let user = User()
let userName = value?["username"] as? String ?? ""
let email = value?["email"] as? String ?? ""
let profileImageUrl = value?["profileImage"] as? String ?? ""
user.userName = userName
user.email = email
user.profileImageUrl = profileImageUrl
print(user)
self.users.append(user)
DispatchQueue.main.async {
self.friendsTableView.reloadData()
}
print(user.userName!, user.email!)
// print(snapshot)
}, withCancel: nil)
}
}
最佳答案
@Taylor M 是正确的。这些是异步网络操作,因此您无法确定哪一个将首先完成。但是,由于 fetchuser
依赖于 fetchfriends
中生成的数据(即 userIds
中会有值),您可以简单地添加一个闭包作为fetchfriends
的参数:
func fetchfriends (_ completion: ((Void) -> Void)?) {
ref.child("users").child(userID!).child("friends").observeSingleEvent(of: .value, with: { (snapshot) in
if let value = snapshot.value as? NSDictionary {
let userName = value["username"] as? String ?? ""
let friendid = value["userid"] as? String ?? ""
self.userIds.append(friendid)
self.userspresent = true
print(userName, friendid)
// call the closure function upon completion
completion?()
}
})
现在,当您在 viewDidLoad
中调用 fetchfriends
时,只需执行以下操作:
fetchfriends {
// this will be called when the friends are successfully fetched
self.fetchuser()
}
关于swift - 在 swift 中首先运行第一个函数后调用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43033744/