gpt4 book ai didi

ios - Swift 3 - viewdidload 中的函数未完全执行

转载 作者:行者123 更新时间:2023-11-28 12:13:56 24 4
gpt4 key购买 nike

我在 viewDidLoad 中使用了一个附加数组的函数,该数组用于其他函数。但是当我执行我的程序时,viewDidLoad 中的函数并不完全执行所以我的 array 仍然是空的。请帮助我。

我的代码:-

 override func viewDidLoad() {
super.viewDidLoad()
self.getAllUsers()
self.fetchData()
}
func getAllUsers(){
ref = Database.database().reference()
ref.child("users").observe(.value, with: { (snapshot) in
if let result = snapshot.children.allObjects as? [DataSnapshot] {
for child in result {
var userid = child.key
print(userid)
self.uuid.append(userid)
}
}
if self.uuid.contains((Auth.auth().currentUser?.uid)!) {
print("Id matched")
}
})

let array = ["Frodo", "sam", "wise", "gamgee"]
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
print(array[randomIndex])

}
func fetchData() {
let randomIndex = Int(arc4random_uniform(UInt32(uuid.count)))
print(uuid[randomIndex])
print(randomIndex)
randomI = randomIndex
Message.downloadAllMessages(forUserID: uuid[randomIndex], completion: {[weak weakSelf = self] (message) in
weakSelf?.items.append(message)
weakSelf?.items.sort{ $0.timestamp < $1.timestamp }
DispatchQueue.main.async {
if let state = weakSelf?.items.isEmpty, state == false {
weakSelf?.tableView.reloadData()
weakSelf?.tableView.scrollToRow(at: IndexPath.init(row: self.items.count - 1, section: 0), at: .bottom, animated: false)
}
}
})
Message.markMessagesRead(forUserID: uuid[randomIndex])
}

最佳答案

尝试在完成 block 后调用 self.fetchData()。您在完成之前调用 self.fetchData()

 override func viewDidLoad() {
super.viewDidLoad()
self.getAllUsers()

}
func getAllUsers(){
ref = Database.database().reference()
ref.child("users").observe(.value, with: { (snapshot) in
if let result = snapshot.children.allObjects as? [DataSnapshot] {
for child in result {
var userid = child.key
print(userid)
self.uuid.append(userid)
}
}

if self.uuid.contains((Auth.auth().currentUser?.uid)!) {
print("Id matched")
}
self.fetchData()// call your method after compeletion block
})

let array = ["Frodo", "sam", "wise", "gamgee"]
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
print(array[randomIndex])

}
func fetchData() {
let randomIndex = Int(arc4random_uniform(UInt32(uuid.count)))
print(uuid[randomIndex])
print(randomIndex)
randomI = randomIndex
Message.downloadAllMessages(forUserID: uuid[randomIndex], completion: {[weak weakSelf = self] (message) in
weakSelf?.items.append(message)
weakSelf?.items.sort{ $0.timestamp < $1.timestamp }
DispatchQueue.main.async {
if let state = weakSelf?.items.isEmpty, state == false {
weakSelf?.tableView.reloadData()
weakSelf?.tableView.scrollToRow(at: IndexPath.init(row: self.items.count - 1, section: 0), at: .bottom, animated: false)
}
}
})
Message.markMessagesRead(forUserID: uuid[randomIndex])
}

关于ios - Swift 3 - viewdidload 中的函数未完全执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47508046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com