Using Segmented control with firebase is not selecting the accurate document when performing the action using the table cell button.
I am using segmented control with tableview in Swift IOS and Firestore database,
I am able to load the documents from database as per the segment control requirement. but when I tap on the button of the table cell it is processing action only on one document, not the accurate one, how should I ensure that table cell button process the document related to that particular id of the document only, below is the code I am sharing
class IPViewController: UIViewController {
@IBOutlet var segmentControl:UISegmentedControl!
@IBOutlet var tableView: UITableView!
var pendingPost:[Pending] = []
var completedPost:[Completed] = []
var postKey:String = ""
var db: Firestore!
var postAuthorId:String = ""
var postAuthorname:String = ""
var PostTitle:String = ""
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
// Do any additional setup after loading the view.
retrieveAllPosts()
}
func retrieveAllPosts(){
let postsRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).collection("Detaling2").limit(to: 50)
postsRef.addSnapshotListener { (snapshot, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let snapshot = snapshot {
for document in snapshot.documents {
let data = document.data()
let username = data["post_author_username"] as? String ?? ""
let postTitle = data["postTitle"] as? String ?? ""
let newSourse = Pending(_documentId: document.documentID, _username: username, _postTitle: postTitle, _postcategory: postcategory)
self.pendingPost.append(newSourse)
}
self.tableView.reloadData()
}
}
}
}
func retrieveAllPosts2(){
let postsRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).collection("Detailing1").limit(to: 50)
postsRef.addSnapshotListener { (snapshot, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let snapshot = snapshot {
for document in snapshot.documents {
let data = document.data()
//self.postKey = document.documentID
let username = data["post_author_username"] as? String ?? ""
let postTitle = data["postTitle"] as? String ?? ""
let newSourse1 = Completed(_documentId: document.documentID, _username: username, _postTitle: postTitle)
self.completedPost.append(newSourse1)
}
self.tableView.reloadData()
}
}
}
}
@IBAction func indexChanged(_ sender: UISegmentedControl) {
switch segmentControl.selectedSegmentIndex
{
case 0:
self.pendingPost.removeAll()
retrieveAllPosts()
case 1:
self.completedPost.removeAll()
retrieveAllPosts2()
default:
break
}
//self.tableView.reloadData()
}
@objc func toComments(_ sender: AnyObject) {
let commentbutton = sender as! UIButton
let post = pendingPost[commentbutton.tag]
postKey = post._documentId // or what key value it is
print("hello")
performSegue(withIdentifier: "IPtoComments", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var vc = segue.destination as! CommentListViewController
vc.postId = postKey
}
@objc func favupdate(_ sender: AnyObject) {
let commentbutton = sender as! UIButton
let post = pendingPost[commentbutton.tag]
postKey = post._documentId // or what key value it is
//print(postKey + "hello777777")
let userMarkRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).collection("marked_posts").document(postKey)
let postRef = Firestore.firestore().collection("posts").document(postKey)
postRef.getDocument{(document, error) in
if let document = document, document.exists{
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
self.postAuthorId = document.get("post_author_id") as! String
self.postAuthorname = document.get("post_author_username") as! String
self.PostTitle = document.get("postTitle") as! String
self.postContent = document.get("postContent") as! String
self.postAuthorEmail = document.get("post_author_email") as! String
self.postCategory = document.get("postcategory") as! String
self.postAuthorfullname = document.get("post_author_fullname") as! String
self.postAuthorGender = document.get("post_author_gender") as! String
self.postAuthorPicUrl = document.get("post_user_profile_pic_url") as! String
// let l11:Bool = document.get("l1") as! Bool
// self.postTimeStamp = document.get("post_timeStamp") as! String
self.postAuthorSpinnerC = document.get("post_author_spinnerC") as! String
}
let postObject = [
"post_author_id": self.postAuthorId,
"post_author_username": self.postAuthorname,
"postTitle": self.PostTitle
] as [String : Any]
userMarkRef.setData(postObject, merge: true) { (err) in
if let err = err {
print(err.localizedDescription)
}
print("Successfully set new user data")
}
}
}
@objc func favupdate1(_ sender: AnyObject) {
let commentbutton = sender as! UIButton
let post = completedPost[commentbutton.tag]
postKey = post._documentId
let userMarkRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).collection("details1").document(postKey)
let postRef = Firestore.firestore().collection("posts").document(postKey)
postRef.getDocument{(document, error) in
if let document = document, document.exists{
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
self.postAuthorId = document.get("post_author_id") as! String
self.postAuthorname = document.get("post_author_username") as! String
self.PostTitle = document.get("postTitle") as! String
}
let postObject = [
"post_author_id": self.postAuthorId,
"post_author_username": self.postAuthorname,
"postTitle": self.PostTitle
] as [String : Any]
userMarkRef.setData(postObject, merge: true) { (err) in
if let err = err {
print(err.localizedDescription)
}
print("Successfully set new user data")
}
}
}
}
extension IPViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var value = 0
switch segmentControl.selectedSegmentIndex{
case 0:
value = pendingPost.count
break
case 1:
value = completedPost.count
break
default:
break
}
return value
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ipwcell", for: indexPath) as! IPWCELL
switch segmentControl.selectedSegmentIndex{
case 0:
cell.pending1 = pendingPost[indexPath.row]
cell.commentbuttonIp.tag = indexPath.row
cell.commentbuttonIp.addTarget(self, action: #selector(toComments(_:)), for: .touchUpInside)
cell.favoritebutton1.addTarget(self, action: #selector(favupdate(_:)), for: .touchUpInside)
break
case 1:
cell.completed1 = completedPost[indexPath.row]
cell.commentbuttonIp.tag = indexPath.row
cell.commentbuttonIp.addTarget(self, action: #selector(toComments(_:)), for: .touchUpInside)
cell.favoritebutton1.addTarget(self, action: #selector(favupdate1(_:)), for: .touchUpInside)
break
default:
break
}
return cell
}
}
@objc func favupdate(_ sender: AnyObject) {
if segmentView.selectedSegmentIndex == 0 {
let commentbutton = sender as! UIButton
let post = pendingPost[commentbutton.tag]
postKey = post._documentId // or what key value it is
//print(postKey + "hello777777")
let userMarkRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).collection("marked_posts").document(postKey)
let postRef = Firestore.firestore().collection("posts").document(postKey)
postRef.getDocument{(document, error) in
if let document = document, document.exists{
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
self.postAuthorId = document.get("post_author_id") as! String
self.postAuthorname = document.get("post_author_username") as! String
self.PostTitle = document.get("postTitle") as! String
self.postContent = document.get("postContent") as! String
self.postAuthorEmail = document.get("post_author_email") as! String
self.postCategory = document.get("postcategory") as! String
self.postAuthorfullname = document.get("post_author_fullname") as! String
self.postAuthorGender = document.get("post_author_gender") as! String
self.postAuthorPicUrl = document.get("post_user_profile_pic_url") as! String
// let l11:Bool = document.get("l1") as! Bool
// self.postTimeStamp = document.get("post_timeStamp") as! String
self.postAuthorSpinnerC = document.get("post_author_spinnerC") as! String
}
let postObject = [
"post_author_id": self.postAuthorId,
"post_author_username": self.postAuthorname,
"postTitle": self.PostTitle
] as [String : Any]
userMarkRef.setData(postObject, merge: true) { (err) in
if let err = err {
print(err.localizedDescription)
}
print("Successfully set new user data")
}
}
}else {
let commentbutton = sender as! UIButton
let post = completedPost[commentbutton.tag]
postKey = post._documentId
let userMarkRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).collection("details1").document(postKey)
let postRef = Firestore.firestore().collection("posts").document(postKey)
postRef.getDocument{(document, error) in
if let document = document, document.exists{
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
self.postAuthorId = document.get("post_author_id") as! String
self.postAuthorname = document.get("post_author_username") as! String
self.PostTitle = document.get("postTitle") as! String
}
let postObject = [
"post_author_id": self.postAuthorId,
"post_author_username": self.postAuthorname,
"postTitle": self.PostTitle
] as [String : Any]
userMarkRef.setData(postObject, merge: true) { (err) in
if let err = err {
print(err.localizedDescription)
}
print("Successfully set new user data")
}
}
}
}
@objc func toComments(_ sender: AnyObject) {
if segmentView.selectedSegmentIndex == 0 {
let commentbutton = sender as! UIButton
let post = pendingPost[commentbutton.tag]
postKey = post._documentId // or what key value it is
print("hello")
performSegue(withIdentifier: "IPtoComments", sender: self)
}else {
let commentbutton = sender as! UIButton
let post = pendingPost[commentbutton.tag]
postKey = post._documentId // or what key value it is
print("hello")
performSegue(withIdentifier: "IPtoComments", sender: self)
}
}