使用Firebase Firestore在TableViewCell中更新按钮UI

时间:2018-04-02 10:37:55

标签: swift uitableview firebase google-cloud-firestore

我的应用程序中的“关注”按钮和“赞”按钮都存在同样的问题。

我在Firebase Firestore文档中看到了如何在按下时添加数据以及如何删除记录,但是,在查看加载时,我无法更新要选择的按钮的初始状态。 / p>

这会在awakeWithNib中完成吗?你会添加一个快照监听器吗?

FollowerCell.swift

class FollowerCell: UITableViewCell {

// MARK: - Outlets
@IBOutlet weak var friendImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var followButton: SpringButton!

// MARK: - Variables
var userId:String!
var db:Firestore!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    friendImageView.layer.masksToBounds = true

    db = Firestore.firestore()

    self.setFollowingButton()
}

// MARK: - Functions
func setFollowingButton() {
    if let currentUser = Auth.auth().currentUser {
        let followerDB = db.collection("users").document(currentUser.uid).collection("followers").whereField("follower", isEqualTo: true)
        followerDB.getDocuments { (querySnapshot, error) in
            if let error = error {
                print("Error getting documents: \(error)")
            } else {
                DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
                    self.followButton.isSelected = true
                })
            }
        }
    }
}

@IBAction func followButtonPressed(_ sender: UIButton) {
    if followButton.isSelected == true {
        followButton.isSelected = false
        // add follower
        if let user = Auth.auth().currentUser {
            Firestore.firestore().collection("users").document(user.uid).collection("following").document("\(userId!)").setData([
                "name":self.nameLabel.text ?? "",
                "following":true
            ])  { err in
                if let err = err {
                    print("Error writing document: \(err)")
                } else {
                    print("\(self.userId!) added to followers")
                }
            }
        }
    } else {
        followButton.isSelected = true
        // delete following
        if let user = Auth.auth().currentUser {
            Firestore.firestore().collection("users").document(user.uid).collection("following").document("\(userId!)").delete() { err in
                if let err = err {
                    print("Error removing document: \(err)")
                } else {
                    print("\(self.userId!) successfully removed!")
                }
            }
        }
    }

}

1 个答案:

答案 0 :(得分:0)

class FollowersTableViewController: UITableViewController {

// MARK: - Variables
var db:Firestore!
let storage = Storage.storage().reference()
var followerArray = [User]()
var followingArray = [String]()

// MARK: - ViewDidLoad
override func viewDidLoad() {
    super.viewDidLoad()

    db = Firestore.firestore()

    SVProgressHUD.show()
    getFollowers()
    getFollowing()

    self.tableView.reloadData()

}

// MARK: - Table view data source

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

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

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "followerCell", for: indexPath) as! FollowerCell

    // Configure the cell...
    let user = followerArray[indexPath.row]

    cell.nameLabel.text = user.name
    cell.userId = user.documentId
    // Set follow button state
    if followingArray.contains(cell.userId) {
        cell.followButton.isSelected = false
    } else {
        cell.followButton.isSelected = true
    }

    let userImageRef = storage.child("\(user.documentId)"+"/profile_pic.jpg")
    // Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
    userImageRef.getData(maxSize: 1 * 1024 * 1024) { (data, error) in
        if let error = error {
            // Uh-oh, an error occurred! Display Default image
            print("Error - unable to download image: \(error)")
            cell.friendImageView.image = UIImage(named: "userProfileGray")
        } else {
            // Data for "locationImages/(locationId).jpg" is returned
            cell.friendImageView.image = UIImage(data: data!)
        }
        SVProgressHUD.dismiss()
    }

    return cell
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 71
}

// MARK: - Functions
func getFollowers() {
    if let user = Auth.auth().currentUser {
        let followingDB = db.collection("users").document("\(user.uid)").collection("followers").whereField("follower", isEqualTo: true)
        followingDB.getDocuments { (querySnapshot, error) in
            if let error = error {
                print("Error getting documents: \(error)")
            } else {
                for document in (querySnapshot?.documents)! {
                    self.followerArray.append(User(name: document["name"] as! String, documentId: document.documentID))
                }
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }
    }
}

func getFollowing() {
    if let currentUser = Auth.auth().currentUser {
        let followingDB = db.collection("users").document(currentUser.uid).collection("following").whereField("following", isEqualTo: true)
        followingDB.getDocuments { (querySnapshot, error) in
            if let error = error {
                print("Error getting documents: \(error)")
            } else {
                for document in (querySnapshot?.documents)! {
                    self.followingArray.append(document.documentID)
                }
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }
    }
}

}