Swift 3.1中Firebase如何获取指定房间members的name和photoURL并展示到TableView
Hey there! Let's walk through how to retrieve the members data (excluding the room creator) from your Firebase database and show them in your TableView. Here's a step-by-step breakdown with code tailored to your Swift 3.1 setup:
1. Define a Model for Participants
First, create a simple struct to hold each member's data—this will make it easier to manage your TableView data source:
struct Participant { let name: String let photoURL: URL? } // Declare your data source array somewhere in your view controller var participants: [Participant] = []
2. Fetch and Filter Members from Firebase
Once you get the marker snapshot from your existing query, you can dive into the members subnode, filter out the creator, and populate your data source:
Assuming your Firebase database structure looks like this (adjust based on your actual setup):
markers - [markerId] - key: "your-room-key" - creatorUid: "uid-of-the-creator" // Critical for filtering - members - [userId1] - name: "Member Name" - photoURL: "https://example.com/avatar.jpg" - [userId2] - name: "Another Member" - photoURL: "https://example.com/avatar2.jpg"
Here's the updated Firebase observation code:
let refParticipants = refDatabase.child("markers").queryOrdered(byChild: "key").queryEqual(toValue: room.key) refParticipants.observe(.childAdded, with: { snapshot in // First, get the creator's UID from the marker snapshot (adjust the path if your field name differs) guard let creatorUid = snapshot.childSnapshot(forPath: "creatorUid").value as? String else { print("Could not retrieve creator UID") return } // Access the members subnode snapshot let membersSnapshot = snapshot.childSnapshot(forPath: "members") // Iterate through each member entry for memberChild in membersSnapshot.children { guard let memberSnapshot = memberChild as? DataSnapshot, let memberData = memberSnapshot.value as? [String: Any], let memberName = memberData["name"] as? String, let photoURLString = memberData["photoURL"] as? String, let photoURL = URL(string: photoURLString) else { // Skip entries with missing data continue } // Exclude the creator by comparing their UID to the member's snapshot key if memberSnapshot.key != creatorUid { let participant = Participant(name: memberName, photoURL: photoURL) self.participants.append(participant) } } // Refresh the TableView on the main thread (Firebase callbacks run in background) DispatchQueue.main.async { self.tableView.reloadData() } })
Notes on Filtering:
- If your creator is identified by a different field (e.g., an
isCreatorboolean in each member entry), adjust the filter condition to:if memberData["isCreator"] as? Bool != true { // Add to participants }
3. Update TableView Data Source Methods
Connect your data source array to the TableView by implementing the required methods:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return participants.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Replace "ParticipantCell" with your cell identifier let cell = tableView.dequeueReusableCell(withIdentifier: "ParticipantCell", for: indexPath) as! ParticipantCell let participant = participants[indexPath.row] cell.nameLabel.text = participant.name // Load the avatar image (use libraries like SDWebImage or Kingfisher for easy async loading) if let avatarURL = participant.photoURL { // Example with SDWebImage: cell.avatarImageView.sd_setImage(with: avatarURL, placeholderImage: UIImage(named: "default-avatar")) } else { cell.avatarImageView.image = UIImage(named: "default-avatar") } return cell }
4. Optional: Handle Real-Time Updates
If you want the TableView to update when members are added/removed, switch to using the .value event instead of .childAdded, or add observers for .childChanged, .childRemoved to keep your data source in sync.
内容的提问来源于stack exchange,提问作者Ghiggz Pikkoro

