简体   繁体   中英

How would I implement friends relationship between users in Firebase Swift?

How would I go about implementing a friends relationship between users, using Firebase in swift?

The following is my current DataService.swift file.

import Foundation
import Firebase

let DB_BASE = Database.database().reference()

class DataService {
    // creates instance of the class inside itself
    static let instance = DataService()

    private var _REF_BASE = DB_BASE
    private var _REF_USERS = DB_BASE.child("users")

    var REF_BASE: DatabaseReference {
        return _REF_BASE
    }

    var REF_USERS: DatabaseReference {
        return _REF_USERS
    }

    func createDBUser(uid: String, userData: Dictionary<String,Any>) {
        REF_USERS.child(uid).updateChildValues(userData)
    }

}

Thanks :)

Not sure this is a very complete answer but may get you going in the right direction

Assume we have three users in Firebase and there is data is stored in a /users node. Larry (uid_0) has two friends, Moe and Curly

users
  uid_0
    name: "Larry"
    friends:
       uid_1: true
       uid_2: true
  uid_1
    name: "Moe"
  uid_2
    name: "Curly"

The code to write the friends node is something like this

let usersRef = fbRed.child("users")
let uid0Ref = usersRef.child("uid_0")
let friendsRef = uid0Ref.child("friends")
friendsRef.child("uid_1").setValue(true)
friendsRef.child("uid_2").setValue(true)

That's pretty verbose and could be condensed but leaving that way for readability.

Note that if you are going to do queries or other functions in the future, this is probably not the best solution.

Each user should have a list of references to other users via their uid. Do not store the entire friend user data object under each user. This will greatly inflate your database.

users ->
    "uid1" ->
        friendUids ->
            0 ->
                "uid2"
            1 ->
                "uid3"
    "uid2" ->
        friendUids ->
            0 ->
                "uid1"
    "uid3" ->
        friendUids ->
            0 ->
                "uid1"

Assuming you have a static decode function on your user to handle the JSON from Firebase, all you need to do to retrieve the user data is:

extension DataService {

    func requestUserWithUid(_ uid: String, completion: @escaping (User?) -> Void) {
        REF_USERS.child(uid).observeSingleEvent(of: .value) { snapshot in
            completion(User.decode(snapshot.value))
        }
    }

    func requestFriendsForCurrentUser(completion: @escaping ([User?]?) -> Void) {
        var friends = [User?]()

        guard let uid = Auth.auth().currentUser?.uid else {
            completion(.none)
            return
        }

        requestUserWithUid(uid) { user in
            guard let user = user else {
                completion(.none)
                return
            }

            for friendUid in user.friendUids {
                requestUserWithUid(friendUid) { friend in
                    friends.append(friend)
                }
            }

            completion(friends)
        }
    }
}

This is just limited example of many of how you could implement it. Let's assume your user data object has a name and we want to display a list of friends' names.

class FriendView: UIView, UITableViewDataSource {

    fileprivate var friends = [User?]()

    fileprivate let tableView = UITableView(frame: .zero, style: .plain)

    // ----------------------------------------------------------------------------
    // MARK: UIView
    // ----------------------------------------------------------------------------

    override init(frame: CGRect) {
        super.init(frame: frame)

        addSubview(tableView)

        tableView.frame = frame
        tableView.dataSource = self

        loadFriends()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder :) has not been implemented")
    }

    // ----------------------------------------------------------------------------
    // MARK: Private
    // ----------------------------------------------------------------------------

    fileprivate func loadFriends() {
        DataService.instance.requestFriendsForCurrentUser() { friends in
            if let friends = friends {
                self.friends = friends
                self.tableView.reloadData()
            }
        }
    }

    // ----------------------------------------------------------------------------
    // MARK: UITableViewDataSource
    // ----------------------------------------------------------------------------

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return friends.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = friends[indexPath.row]?.name
        return cell
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM