TableView Not Updating After Item Is Added To Array - swift

I am building an app that uses the Twitter API to post to a user's Twitter and load those tweets in a TableView. The table loads correctly when the app first launches. However, after composing and posting a Tweet (confirmed that the Tweet is posted and in the array) the table view is still displaying the same tweets prior without the newly created one. I thought it might have something to do with the asynchronous code so I implemented the DispatchQueue in the refreshData() function. The table view is still not loading the most recently added tweet. How can I change the refreshData() function so that the table updates when Tweet is posted successfully?
import UIKit
import OAuthSwift
class FeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var tweetText: UITextField!
var user: User!
var tweets = [Tweet]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
self.tableView.rowHeight = 200
let consumerSecret = user.consumerSecret
let consumerKey = user.consumerKey
let oAuthToken = user.oAuthToken
let oAuthSecret = user.oAuthSecret
let oauthswift = user.oauthswift
let screen_name = user.screen_name
print("Feed Consumer Secret: \(consumerSecret)")
print("Feed Consumer Key: \(consumerKey)")
print("Feed Auth Token: \(oAuthToken)")
print("Feed Auth Secret: \(oAuthSecret)")
print("Screen Name: \(screen_name)")
loadFeed(oauthswift: oauthswift)
// Do any additional setup after loading the view.
}
#IBAction func postButtonPushed(_ sender: Any) {
let oauthswift = user.oauthswift
let url = "https://api.twitter.com/1.1/statuses/update.json?status="
let tweet_url = tweetText.text
let encoded_tweet = tweet_url?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)
let new_url = url + encoded_tweet!
let _ = oauthswift.client.post(
new_url, parameters: [:],
success: { response in
let dataString = response.string!
let jsonDict = try? response.jsonObject()
let jsonDict2 = jsonDict as! Dictionary<String,Any>
let tweetText2 = jsonDict2["text"]!
let jsonDict4 = jsonDict2["user"] as! Dictionary<String,Any>
let username = jsonDict4["screen_name"]!
let newTweet = Tweet(tweetText: tweetText2 as! String, username: username as! String)
self.tweets.append(newTweet)
print(username)
//print(dataString)
self.loadFeed(oauthswift: oauthswift)
self.tweetText.text = ""
},
failure: { error in
print(error)
}
)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let tweet = tweets[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? PostCell {
cell.configureCell(tweet: tweet)
return cell
} else {
return PostCell()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
func loadFeed(oauthswift: OAuth1Swift){
print("LOAD FEED")
let _ = oauthswift.client.get(
"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=\(user.screen_name)", parameters: [:],
success: { response in
let jsonDict = try? response.jsonObject()
let jsonDict2 = jsonDict as! Array<Dictionary<String,Any>>
let arrayCount = jsonDict2.count
for index in 0...arrayCount - 1 {
let jsonDict4 = jsonDict2[index]["user"] as! Dictionary<String,Any>
let tweetText = jsonDict2[index]["text"]!
let username = jsonDict4["screen_name"]!
let newTweet = Tweet(tweetText: tweetText as! String, username: username as! String)
self.tweets.append(newTweet)
print(tweetText)
}
self.refreshData()
}, failure: { error in
print(error)
}
)
}
func refreshData() {
DispatchQueue.main.async{
self.tableView.reloadData()
}
}
}
PostCell.swift
import UIKit
class PostCell: UITableViewCell {
#IBOutlet weak var userLabel: UILabel!
#IBOutlet weak var tweetLabel: UILabel!
var tweet: Tweet!
func configureCell(tweet: Tweet) {
self.userLabel.text = "#\(tweet.username)"
self.tweetLabel.text = tweet.tweetText
print(tweet.tweetText)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}

Since you are sure that Twitter accepted the post and you appended the new Tweet to the data source there is no need for a full reloadData. You can display just the new row in the table.
In FeedViewController, in method postButtonPushed, inside the oauthswift.client.post's success clousure right after this line self.tweets.append(newTweet) add this:
DispatchQueue.main.async {
self.tableView.beginUpdates()
self.tableView.insertRows(at: [IndexPath(item: self.tweets.count-1, section: 0)],
with: .automatic)
self.tableView.endUpdates()
}

Related

How to add data into Firestore Swift by tapping on a cell

I have more restaurants , each have diferent food.Look here
This is how im retrieving data from the Firestore. In the previous controller I have a list of restaurants, each contains a list food.
struct Food {
var photoKeyRestaurant: String
var foodName: String
var foodDescription: String
var restaurantName: String
var priceFood: Int
}
class RestaurantViewController: UIViewController {
var restaurantName: String!
var food: [Food] = []
private let tableView: UITableView = {
let table = UITableView()
return table
}()
func getDatabaseRecords() {
let db = Firestore.firestore()
// Empty the array
food = []
db.collection("RestaurantViewController").whereField("restaurantName", isEqualTo: restaurantName).getDocuments { (snapshot, error) in
if let error = error {
print(error)
return
} else {
for document in snapshot!.documents {
let data = document.data()
let newEntry = Food(photoKeyRestaurant: data["photoKeyRestaurant"] as! String, foodName: data["foodName"] as! String, foodDescription: data["foodDescription"] as! String, restaurantName: data["restaurantName"] as! String , priceFood: data["priceLabel"] as! Int
)
self.food.append(newEntry)
}
}
DispatchQueue.main.async {
// self.datas = self.filteredData
self.tableView.reloadData()
}
}
}
How can I add the data of the selected cell by pressing on + to Firestore in this function ?
I'vrea create a protocol in my FoodTableViewCell , and I've called it in the RestaurantViewController.
func diddTapButtonCell(_ cell: FoodTableViewCell) {
let db = Firestore.firestore()
db.collection("cart").addDocument.(data: foodName) { (err) in
}
Edited: Added Table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return food.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FoodTableViewCell", for: indexPath) as! FoodTableViewCell
cell.delegate = self
let mancare = food[indexPath.row]
let storageRef = Storage.storage().reference()
let photoRef = storageRef.child(mancare.photoKeyRestaurant)
cell.foodImage.sd_setImage(with: photoRef)
cell.descriptionLabel.text = mancare.foodDescription
cell.foodNameLabel.text = mancare.foodName
cell.priceLabel.text = "\(mancare.priceFood) lei"
//Fac ca imaginea sa fie cerc - start
cell.foodImage.layer.borderWidth = 1
cell.foodImage.layer.masksToBounds = false
cell.foodImage.layer.borderColor = UIColor.black.cgColor
cell.foodImage.layer.cornerRadius = cell.foodImage.frame.height/2
cell.foodImage.clipsToBounds = true
//Fac ca imaginea sa fie cerc - finish
return cell
}
This is my tableview cell code
protocol CustomCellDelegate {
func diddTapButtonCell (_ cell: FoodTableViewCell)
}
class FoodTableViewCell: UITableViewCell {
var delegate: CustomCellDelegate?
#IBOutlet weak var foodImage: UIImageView!
#IBOutlet weak var foodNameLabel: UILabel!
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet weak var priceLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
#IBAction func addToCart(_ sender: Any) {
delegate?.diddTapButtonCell(self)
}
}
https://firebase.google.com/docs/firestore/manage-data/add-data
And here is an example from one of my projects for adding data to firestore.
func updateDocument(rootCollection : String, doc: String, newValueDict: [String : Any], completion:#escaping (Bool) -> Void = {_ in }) {
let db = Firestore.firestore()
db.collection(rootCollection).document(doc).setData(newValueDict, merge: true){ err in
if let err = err {
print("Error writing document: \(err)")
completion(false)
}else{
completion(true)
}
}
}

XCode 12/Swift 4 Custom Cells not displaying on UI Table Cell View

Ok so, I am trying to make a custom table that has a news feed from newsapi, from my debugging: the api calls and such get made and the data is acessed, its just that it doesnt display on the table, it shows up as a blank table.
Here is the code:
This is from the "first view controller" as I am using the tabbed template
import UIKit
class FirstViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var articles: [Article]? = []
override func viewDidLoad() {
super.viewDidLoad()
fetchArticles()
}
func fetchArticles(){
let urlRequest = URLRequest(url: URL(string: "https://newsapi.org/v2/top-headlines?country=us&?category=business&apiKey=sorrynotgivingmykey")!)
let task = URLSession.shared.dataTask(with: urlRequest){(data,response,error) in
if error != nil{
print(error)
return
}
self.articles = [Article]()
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
if let articlesFromJson = json["articles"] as? [[String: AnyObject]]{
for articlesFromJson in articlesFromJson{
let article = Article()
if let title = articlesFromJson["title"] as? String, let desc = articlesFromJson["description"] as? String, let url = articlesFromJson["url"] as? String, let imageToUrl = articlesFromJson["urlToImage"] as? String, let date = articlesFromJson["publishedAt"] as? String{
article.headline = title
article.desc = desc
article.url = url
article.imageUrl = imageToUrl
article.date = date
// print(article.date)
// print(article.headline)
}
self.articles?.append(article)
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}catch let error{
print(error)
}
}
task.resume()
// print(articles)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.articles!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "worklmao", for: indexPath) as! ArticleCell
cell.title.text = self.articles?[indexPath.item].headline
cell.desc.text = self.articles?[indexPath.item].desc
cell.date.text = self.articles?[indexPath.item].date
print("lol lmao hahax help fuck shit")
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
1
}
}
And this is the cell classes I used for the articles
import UIKit
class ArticleCell: UITableViewCell {
#IBOutlet weak var date: UILabel!
#IBOutlet weak var desc: UILabel!
#IBOutlet weak var title: UILabel!
#IBOutlet weak var ImgView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
This is the article class
import UIKit
class Article: NSObject {
var headline: String?
var desc: String?
var url: String?
var date: String?
var imageUrl: String?
}
and bare in mind I did setup the class for the cell properly(at least I think
Still, this is what I get:
Don't forget to connect dataSource and delegate for tableView.
Change your tableView outlets to this:
#IBOutlet weak var tableView: UITableView! {
didSet {
tableView.delegate = self
tableView.dataSource = self
}
}
Some points:
You don't have to declare articles array as optional. Simply do this :
var articles = [Article]()
Try to learn about codables for JSON parsing.

Firebase Realtime Database and Xcode: To allow each user to read their own data NOT all the data

I have added this to my code:
let userID = Auth.auth().currentUser!.uid
ref = Database.database().reference().child(userID);
Thinking this would work and give me the results I needed, as my rules are right, however the app just comes up with a blank table instead of it filled in with the details. Which is really weird!
Firstly here are my firebase rules:
{
"rules": {
"jobs": {
"$uid": {
".read": "auth.uid === $uid"
}
}
}
}
Here is my firebase database:
FirebaseDatabase
Here is the Firebase Auth with the UID
FirebaseAuth
Here is my code:
ViewController for Login Page:
import UIKit
import Firebase
import FirebaseAuth
class LoginViewController: UIViewController {
var ref: DatabaseReference!
static var isAlreadyLaunchedOnce = false
#IBOutlet weak var txtemail: UITextField!
#IBOutlet weak var txtpass: UITextField!
var isSignin:Bool = true
override func viewDidLoad() {
super.viewDidLoad()
if FirebaseApp.app() == nil {
FirebaseApp.configure()
}
}
#IBAction func submit(_ sender: UIButton) {
if let email = txtemail.text, let passowrd = txtpass.text
{ Auth.auth().signIn(withEmail: email, password: passowrd) { (user, error) in
if user != nil {
self.performSegue(withIdentifier: "goto", sender : self)
}
else {
let alert = UIAlertController(title: "Username or Password Incorrect", message: nil, preferredStyle: .alert)
let okButton = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(okButton)
self.present(alert, animated: true, completion: nil)
}
}
}
}
}
View controller for Logged in Page
import UIKit
import Firebase
class LoggedInViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var loginlbl: UILabel!
#IBOutlet weak var tbl: UITableView!
var ref: DatabaseReference!
var jobList = [JobModel]()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let job = jobList[indexPath.row]
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell
let job: JobModel
job = jobList[indexPath.row]
cell.lblCol.text = job.collection
cell.lblDel.text = job.delivery
cell.lblShip.text = job.shipper
cell.lblCon.text = job.consignee
cell.lblEmai.text = job.email
cell.lblRef.text = job.reference
cell.lblFreight.text = job.freight
cell.collected.text = job.collected
cell.delivered.text = job.delievered
return cell }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return jobList.count
}
override func viewDidLoad() {
super.viewDidLoad()
if FirebaseApp.app() == nil {
FirebaseApp.configure() }
ref = Database.database().reference().child("jobs");
ref.observe(DataEventType.value) { (snapshot) in
if snapshot.childrenCount>0 {
self.jobList.removeAll()
for jobs in snapshot.children.allObjects as! [DataSnapshot]{
let jobObject = jobs.value as? [String: AnyObject]
let jobId = jobObject?["id"]
let jobShipper = jobObject?["shipper"]
let jobConsignee = jobObject?["consignee"]
let jobEmail = jobObject?["email"]
let jobReference = jobObject?["reference"]
let jobFreight = jobObject?["freight"]
let jobCollection = jobObject?["collection date"]
let jobDelivery = jobObject?["delivery date"]
let jobPod = jobObject?["pod"]
let jobCollected = jobObject?["collected"]
let jobDelivered = jobObject?["delivered"]
let job = JobModel(id: jobId as! String?,
shipper: jobShipper as! String?,
consignee: jobConsignee as! String?,
email: jobEmail as! String?,
reference: jobReference as! String?,
freight: jobFreight as! String?,
collection: jobCollection as! String?,
delivery: jobDelivery as! String?,
pod: jobPod as! String?,
collected: jobCollected as! String?,
delivered: jobDelivered as! String?)
self.jobList.append(job)
}
self.tbl.reloadData()
} } }
override func viewDidAppear(_ animated: Bool) {
Auth.auth().currentUser != nil; do {
self.loginlbl.text = "Hello " + (Auth.auth().currentUser?.email)!
}}
}
Your rules let you access to the children node of jobs. like jobs/user_id_1
So you have to listen to the child instead of the whole jobs node
Database.database().reference().child("jobs");
to
Database.database().reference().child("jobs\loggedInUserID");

Swift MovieDB API Search Bar integration

Everyone, I'm having difficulties finding documentation on how to implement a Search filter for My Movie DB app ill attach my code so far below I've managed to get the data to show up in the table view
The title and Image What I need to do now is being able to filter the movies with a search bar then when clicking on a row it goes to a new View controller displaying expanded information about the movie then a button to "bookmark" save it to core data then appear on a bookmark screen for the user to view later.
Thanks in Advance
My code is here:
import UIKit
import AFNetworking
class ViewController: UIViewController, UITableViewDataSource,
UITableViewDelegate, UISearchBarDelegate {
var movies: [NSDictionary]?
#IBOutlet weak var txtSearch: UITextField!
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
// Do any additional setup after loading the view, typically from a nib.
fetchMovies()
searchBar()
}
func searchBar(){
let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width:
self.view.frame.width, height: 50))
searchBar.delegate = self
searchBar.showsScopeBar = true
searchBar.tintColor = UIColor.lightGray
searchBar.scopeButtonTitles = ["Now Playing"]
self.tableView.tableHeaderView = searchBar
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
{
if searchText == ""{
fetchMovies()
}else{
if searchBar.selectedScopeButtonIndex == 0 {
movies = movies?.filter({ (movies) -> Bool in
return movies.title.lowercased()
})
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return movies?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MovieTableViewCell
let movie = movies![indexPath.row]
let title = movie["title"] as! String
let posterPath = movie["poster_path"] as! String
let baseUrl = "https://image.tmdb.org/t/p/w300/"
let imageUrl = NSURL(string: baseUrl + posterPath)
cell.lblTitle.text = title
cell.imgMovie.setImageWith(imageUrl! as URL)
print("row \(indexPath.row)")
return cell
}
func fetchMovies(){
let apiKey = "2c0a8efe934c162f5535ff33303e70bd"
let url = NSURL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=\(apiKey)")
let request = URLRequest(url: url! as URL, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 10)
let session = URLSession(
configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: OperationQueue.main
)
let task: URLSessionDataTask = session.dataTask(with: request, completionHandler:{(dataOrNil, repsonse, error) in
if let data = dataOrNil {
if let responseDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary{print("response: \(responseDictionary)")
self.movies = responseDictionary["results"] as? [NSDictionary]
self.tableView.reloadData()
}
}
})
task.resume()
}
#IBAction func btnBookmark(_ sender: UIButton) {
}
}

How to access a property of a tableview cell from viewcontroller?

Please see screenshot. There is a repliesTableView, replyTextField and replyButtonin ViewController. repliesTableView cell is called ReplyCell. In ReplyCell there is a commentTableView to list all comments for that reply and a textfField, a commentButton to add new comments.
I have problem when add new replies and new comments. I guess I need to make comments array in ReplyCell empty when I click the Reply button. How can I make this happen? I have no idea how to access comments arrayfrom the root ViewController.
Exact problems: fter clicking commentButton, all comments in every cell doubled. After clicking replyButton, comments went to wrong cell.
Code:
import UIKit
import Firebase
class TopicForumVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
#IBOutlet weak var topicNameLabel: UILabel!
#IBOutlet weak var replyNumberLabel: UILabel!
#IBOutlet weak var repliesTableView: UITableView!
#IBOutlet weak var replyTextField: UITextField!
var topicName:String?
var firstKey:String?
var secondKey:String?
var replies = [String]()
var replyButtonTapped = false
override func viewDidLoad() {
super.viewDidLoad()
repliesTableView.delegate = self
repliesTableView.dataSource = self
replyTextField.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
topicNameLabel.text = self.topicName
loadReplies()
}
func loadReplies() {
self.replies = []
DataService.ds.Categories_Base.child(self.firstKey!).child("Topics").observe(.value, with:{(snapshot) in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
if let topicDict = snap.value as? Dictionary<String,AnyObject> {
if let topic = topicDict["text"] as? String {
if topic == self.topicName {
self.secondKey = snap.key
UserDefaults.standard.setValue(snap.key, forKey: Key_SecondKey)
if let replyDict = topicDict["replies"] as? Dictionary<String,AnyObject> {
for eachDict in replyDict {
if let textDict = eachDict.value as? Dictionary<String,AnyObject> {
if let reply = textDict["text"] as? String {
self.replies.append(reply)
self.replyNumberLabel.text = String(self.replies.count)
}
}
}
}
}
}
}
}
self.repliesTableView.reloadData()
}
})
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return replies.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "ReplyCell") as? ReplyCell {
let reply = replies[indexPath.row]
cell.configureReplyCell(reply: reply)
return cell
} else {
return UITableViewCell()
}
}
#IBAction func replyButtonTapped(_ sender: Any) {
replyButtonTapped = true
if let reply = replyTextField.text, reply != "" {
self.replies = []
DataService.ds.Categories_Base.child(self.firstKey!).child("Topics").child(self.secondKey!).child("replies").childByAutoId().child("text").setValue(reply)
self.repliesTableView.reloadData()
let i = replies.count
for n in 0..<i {
let indexPath = IndexPath(row: n, section: 1)
let cell = repliesTableView.cellForRow(at: indexPath) as! ReplyCell
cell.comments = []
cell.repliesToReplyTableView.reloadData()
}
self.replyTextField.text = ""
self.replyButtonTapped = false
}
}
}
import UIKit
import Firebase
class ReplyCell: UITableViewCell,UITableViewDataSource,UITableViewDelegate, UITextFieldDelegate {
#IBOutlet weak var replyTextView: UITextView!
#IBOutlet weak var repliesToReplyTableView: UITableView!
#IBOutlet weak var commentTextField: UITextField!
var reply:String?
var comments = [String]()
var replyKey:String?
override func awakeFromNib() {
super.awakeFromNib()
self.comments = []
repliesToReplyTableView.delegate = self
repliesToReplyTableView.dataSource = self
commentTextField.delegate = self
loadComments()
}
func configureReplyCell(reply:String) {
self.reply = reply
self.replyTextView.text = self.reply
}
func loadComments() {
self.comments = []
if let firstKey = UserDefaults.standard.value(forKey: Key_FirstKey) as? String, let secondKey = UserDefaults.standard.value(forKey: Key_SecondKey) as? String {
DataService.ds.Categories_Base.child(firstKey).child("Topics").child(secondKey).child("replies").observe(.value, with:{(snapshot) in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
if let replyDict = snap.value as? Dictionary<String,AnyObject> {
if let reply = replyDict["text"] as? String {
if reply == self.reply {
self.replyKey = snap.key
DataService.ds.Categories_Base.child(firstKey).child("Topics").child(secondKey).child("replies").child(snap.key).child("comments").observe(.value, with: { (commentSnapshot) in
if let commentSnapshots = commentSnapshot.children.allObjects as? [FIRDataSnapshot] {
for commentSnap in commentSnapshots {
if let commentDict = commentSnap.value as? Dictionary<String,AnyObject> {
if let comment = commentDict["text"] as? String {
self.comments.append(comment)
}
}
}
}
self.repliesToReplyTableView.reloadData()
})
}
}
}
}
}
})
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let commentCell = tableView.dequeueReusableCell(withIdentifier:"CommentCell")
commentCell?.textLabel?.text = comments[indexPath.row]
return commentCell!
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
#IBAction func commentBtnPressed(_ sender: Any) {
if let comment = commentTextField.text, comment != "" {
self.comments = []
if let firstKey = UserDefaults.standard.value(forKey: Key_FirstKey) as? String, let secondKey = UserDefaults.standard.value(forKey: Key_SecondKey) as? String {
DataService.ds.Categories_Base.child(firstKey).child("Topics").child(secondKey).child("replies").child(self.replyKey!).child("comments").childByAutoId().child("text").setValue(comment)
if let myViewController = parentViewController as? TopicForumVC {
// myViewController.repliesTableView.reloadData()
myViewController.replies = []
}
self.repliesToReplyTableView.reloadData()
self.commentTextField.text = ""
self.replyKey = ""
}
}
}
I don't really know the exact circumstances of what you're building but there are two ideas that may offer some guidance.
1) If your table is displaying content from a data source then you will likely have some kind of reference. E.g. when loading the cells (in this case CustomCell) you'll do something like get the index of the cell and get the same index from the data, and put that data in the cells content. If that's the case, all you have to do on the button click is use tableview.cellForRowAtIndexPath with your sender object, and then remove the array from the data source, e.g. tableDataSource[index] = nil and reload the tableView.
2) If you have a stored property on the CustomCell that you've add specifically for storing this array, then you'd cast the sender object to CustomCell and remove the property, as in Kim's answer.
Hope this helps, but without more information it's kind of hard to tell.
let cell = tableview.cellForRowAtIndexPath(...) as? CustomCell
if cell != nil {
let arr = cell.array
}
BTW: I would re-think storing your array in the cell..