我检索过朋友UID,观察姓名,照片等信息的最佳方式是什么? 现在UidArray持有朋友的uids,我应该为每个uid循环以在Tableview上显示他们的信息吗?
[(1, 'id'),
('Alice Alwen', 'string'),
('12345 Oak Street', 'string'),
('Anytown, US 12345', 'string'),
(0, 'id'),
(123.45, 'amount'),
(2007, 'year'),
('Pontiac', 'string'),
(2, 'id'),
('Bob Bobberson', 'string'),
('1919 Elm Road', 'string'),
('Metropolis, US 11111', 'string'),
(123.45, 'amount'),
(0, 'id'),
(2016, 'year'),
('Sherman Tank', 'string'),
(2105, 'year'),
('Bradley Fighting Vehicle', 'string'),
(5, 'id'),
('Carl Carlson', 'string'),
('9854 Willow Way #1', 'string'),
('Gotham City, GA 34567', 'string'),
('1,001.00', 'string'),
('2,300.00', 'string'),
(2015, 'year'),
('Batmobile - used', 'string')]
用户模型:
let userIdArray = self.UidArray
for id in userIdArray {
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String: Any] else {
return
}
let displayN = dictionary["displayname"] as? String
let Uid = dictionary["uid"] as? String
let ImgUrl = dictionary["urlToImage"] as? String
// Append results to another array, reload table view if loop is done.
我只想获取一次数据。每次通过滚动显示单元格时,我都不想点击数据库。
我想知道根据他们的uid数据获取朋友信息的最佳方法是什么?
答案 0 :(得分:0)
for循环不是必需的并且非常过分,因为Firebase的观察方法中使用的.childAdded
将像用户一样多次调用该函数,就像for循环一样。
func handleFetchAllUsers(_ completion: @escaping ([User]) -> ()) {
DispatchQueue.global(qos: .userInteractive).async {
var data: [User] = []
let reference = Database.database().reference().child("users")
reference.observe(.childAdded, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String: AnyObject] else { return }
let username = dictionary["username"] as? String
let name = dictionary["name"] as? String
let email = dictionary["email"] as? String
let user = User()
user.name = name
user.username = username
user.email = email
data.append(user)
DispatchQueue.main.async {
completion(data)
}
}, withCancel: nil)
}, withCancel: nil)
}
}
您可以像这样调用函数:
var users: [User] = []
handleFetchAllUsers { (user) in // USER IS THE ARRAY OF USERS RETURNED FROM THE FUNCTION
self.users = user
self.collectionView.reloadData() // IF YOU'RE USING A UICOLLECTIONVIEW.
}