У меня есть пользовательская ячейка с кнопками в ячейке. Кнопка работает успешно, изменяя данные в Firebase. Проблема в том, что он ДОБАВЛЯЕТ одну строку с теми же данными данных Ячейки, на которые я нажал.
Вот что происходит, я нажимаю «Следить за именем пользователя« Чу », и в него добавляется одна строка пользователя Чу, код выполнить успешно
Я тестирую печатью и обнаружил, что ArrayFollowers Add Еще одно значение, которое таблица добавляет еще строки. В чем проблема?
До
После
Вот мой код
import UIKit
import FirebaseAuth
import FirebaseDatabase
class FollowersVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate{
// MARK: _ DECLARE
@IBOutlet weak var FollowersTableView: UITableView!
@IBOutlet weak var Searchbar: UISearchBar!
var ref = Database.database().reference()
var ArrayFollowers = [NSDictionary?]()
var FilterArrFollowers = [NSDictionary?]()
// MARK: _ OVERVIEW
override func viewDidLoad() {
super.viewDidLoad()
let userid = Auth.auth().currentUser?.uid
Searchbar.delegate = self
self.FollowersTableView.rowHeight = 67
// retrieve the followers users
ref.child("profile").child(userid!).child("follower").observe(.childAdded, with: {(snapshot) in
let followerid = snapshot.key
self.ref.child("profile").child("\(followerid)").observe(.value, with: {(snapshot) in
let value = snapshot.value as? NSDictionary
self.ArrayFollowers.append(value)
print("AAAAAAAAA",self.ArrayFollowers)
self.FollowersTableView.insertRows(at: [IndexPath(row: self.ArrayFollowers.count-1,section: 0)], with: UITableView.RowAnimation.automatic)
})
})
}
// MARK: - TABLEVIEW DATA SOURCE
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if Searchbar.text != "" {
return FilterArrFollowers.count
}
return self.ArrayFollowers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FollowersCell", for: indexPath) as! FollowersTableCell
let follower : NSDictionary
let userid = Auth.auth().currentUser?.uid
if Searchbar.text != "" {
follower = FilterArrFollowers[indexPath.row]!
}else{
follower = ArrayFollowers[indexPath.row]!
}
if let profileURL = follower["profilepic"] as? String {
cell.Pix.sd_setImage(with: URL(string: profileURL))
cell.Pix.circle()
}
cell.Username.text = follower["username"] as? String
self.ref.child("profile").observe(.childAdded, with: {(snapshot) in
let value = snapshot.value as? NSDictionary
if value == follower{
let followerID = snapshot.ref.key
self.ref.child("profile").child(userid!).child("following").observe( .value, with: { (snapshot) in
if snapshot.hasChild(followerID!){
// check Following?
cell.Followbutton.setTitle("Following", for: .normal)
cell.Followbutton.setTitleColor(.lightGray, for: .normal)
// UNFOLLOW action
cell.followaction = {
cell.Followbutton.setTitle("Follow", for: .normal)
cell.Followbutton.setTitleColor(.systemBlue, for: .normal)
self.ref.child("profile").child(userid!).child("following").child(followerID!).setValue(nil)
self.ref.child("profile").child(followerID!).child("follower").child(userid!).setValue(nil)
}
}else{
// check NOT Following?
cell.Followbutton.setTitle("Follow", for: .normal)
cell.Followbutton.setTitleColor(.systemBlue, for: .normal)
// FOLLOW action
cell.followaction = {
cell.Followbutton.setTitle("Following", for: .normal)
cell.Followbutton.setTitleColor(.lightGray, for: .normal)
self.ref.child("profile").child(userid!).child("following").updateChildValues([followerID!: true], withCompletionBlock: {(error, ref) in
if error != nil {
print(error!)
return
}
})
self.ref.child("profile").child(followerID!).child("follower").updateChildValues([userid!: true], withCompletionBlock: {(error, ref) in
if error != nil {
print(error!)
return
}
})
}
}
// Remove Followers
cell.removeaction = {
self.ref.child("profile").child(userid!).child("follower").child(followerID!).setValue(nil)
self.ref.child("profile").child(followerID!).child("following").child(userid!).setValue(nil)
self.ArrayFollowers.remove(at: indexPath.row)
self.FollowersTableView.deleteRows(at: [indexPath], with: .fade)
}
})
}
})
return cell
}
// MARK: - SEARCH FUNCTION
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredContent(searchText: self.Searchbar.text!)
}
func filteredContent(searchText: String){
self.FilterArrFollowers = self.ArrayFollowers.filter{ user in
let username = user!["username"] as? String
return(username?.lowercased().contains(searchText.lowercased()))!
}
FollowersTableView.reloadData()
}
}
// MARK: _ CELL CLASS
class FollowersTableCell: UITableViewCell{
var followaction : (() -> ()) = {}
var removeaction : (() -> ()) = {}
@IBOutlet weak var Pix: UIImageView!
@IBOutlet weak var Username: UILabel!
@IBOutlet weak var Followbutton: UIButton!
@IBAction func FollowButton(_ sender: Any) {
followaction()
}
@IBAction func removebutton(_ sender: Any) {
removeaction()
}
}