Is it possible to add UITableView in UIScrollView? - ios

The first two are working just fine but when the scroll horizontally to the third view that is table view the data is not getting populated. I am not what is going wrong in my code or it is not possible to achieve table view in scroll view?
The ScrollViewController code is mentioned below -
ScrollViewController
import UIKit
class ViewController: UIViewController {
var land = LandlordList()
var prop = PropertyList()
#IBOutlet weak var myScrollview: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
let v1:ContactLandlord = ContactLandlord(nibName: "ContactLandlord", bundle: nil)
let v2:ContactLandlord2 = ContactLandlord2(nibName: "ContactLandlord2", bundle: nil)
let v3: PropertyTableVC = PropertyTableVC(nibName:"PropertyTableVC", bundle: nil)
self.addChildViewController(v1)
self.myScrollview.addSubview(v1.view)
v1.didMove(toParentViewController: self)
self.addChildViewController(v2)
self.myScrollview.addSubview(v2.view)
v2.didMove(toParentViewController: self)
self.addChildViewController(v3)
self.myScrollview.addSubview(v3.view)
v3.didMove(toParentViewController: self)
self.myScrollview.contentSize = CGSize(width: self.view.frame.width * 3, height: self.view.frame.size.height)
var v2frame: CGRect = v1.view.frame
v2frame.origin.x = self.view.frame.width
v2.view.frame = v2frame
var v3frame:CGRect = v2.view.frame
v3frame.origin.x = self.view.frame.width * 2
v3.view.frame = v3frame
v1.code.text = land.code
v1.titlelbl.text = land.title
v1.fname.text = land.firstName
v1.mname.text = land.middleName
v1.lname.text = land.lastName
v1.salutation.text = land.salutation
v1.add1.text = land.address1
v1.add2.text = land.address2
v1.add3.text = land.address3
v1.city.text = land.city
v1.area.text = land.area
v1.cluster.text = land.cluster
v2.email.text = land.email
v2.aemail.text = land.aemail
v2.cemail.text = land.certificationEmail
v2.memail.text = land.certificationEmail
v2.contact.text = land.contact
v2.hcontact.text = land.homeNumber
v2.wcontact.text = land.workNumber
v2.fcontact.text = land.faxNumber
let v4 = v3.propertyTabel.dequeueReusableCell(withIdentifier: "Cell") as? PropertyCell
v4?.propertyCodeLbl.text = prop.code
v4?.addressLbl.text = prop.address1
}
}
The PropertyTableVC is mentioned below -
PropertyTableVC
import UIKit
import Alamofire
class PropertyTableVC: UITableViewController {
#IBOutlet var propertyTabel: UITableView!
let URL_Landlord_Property_List = "http://127.0.0.1/source/api/LandlordPropertyList.php"
var count: Int = 0
var landlordPropertyArray: [PropertyList]? = []
override func viewDidLoad() {
super.viewDidLoad()
propertyTabel.dataSource = self
propertyTabel.delegate = self
fetchData()
let nibName = UINib(nibName: "PropertyCell", bundle:nil)
self.propertyTabel.register(nibName, forCellReuseIdentifier: "Cell")
}
func fetchData(){
let urlRequest = URLRequest(url: URL(string: URL_Landlord_Property_List)!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if error != nil{
print(error!)
return
}
print(data!)
self.landlordPropertyArray = [PropertyList]()
self.count = (self.landlordPropertyArray?.count)!
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
if let datafromjson = json["landlords_property_list"] as? [[String: AnyObject]] {
print(datafromjson)
for data in datafromjson{
var property = PropertyList()
if let id = data["ID"] as? Int,let code = data["Code"] as? String, let address1 = data["Address"] as? String
{
property.id = id
property.code = code
property.address1 = address1
}
self.landlordPropertyArray?.append(property)
}
print(self.landlordPropertyArray)
DispatchQueue.main.async {
self.propertyTabel.reloadData()
}
}
}catch let error {
print(error)
}
}
task.resume()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (landlordPropertyArray?.count)!
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Configure the cell...
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! PropertyCell
cell.propertyCodeLbl.text = self.landlordPropertyArray?[indexPath.item].code
cell.addressLbl.text = self.landlordPropertyArray?[indexPath.item].address1
return cell
}
}

The data in the tableView is loaded only when you conform to UITableViewDataSource UITableViewdelegate.
Use this , and have numberOfRows() and cellForRowAtIndexPath() in the class.
you will definitely get the populated tableView.

Related

Button in the table cell not working upon tapping

I am using below code for the UITableView, in every cell there are two buttons configured to perform certain actions as shown in the code. Earlier it was working fine, but now As I update this code to new version of Xcode it is not working, whenever I tap on the cell or the button in the cell it doesn't perform any action, neither it shows any error, but it just darkens the half of the cell with grey colour?
Xcode earlier was 10 and now 11, swift 5 version same in both cases
There is one fixed cell at the top and then there is list of cells as per the number of documents in the database
What could be the issue?
for information I am using Swift IOS and cloud firestore database
class HomeViewController: UITableViewController {
var posts = [Post]()
var db: Firestore!
var scores1 = [Scores]()
var postAuthorId:String = ""
var postAuthorname:String = ""
var CommentAuthorName:String = ""
var PostTitle:String = ""
var postAuthorGender:String = ""
var postAuthorEmail:String = ""
var postAuthorfullname:String = ""
var postAuthorSpinnerC:String = ""
var postContent:String = ""
var postCategory:String = ""
var postAuthorPicUrl:String = ""
var postTimeStamp:String = ""
var l11:Int = 0
var postKey:String = ""
private var documents: [DocumentSnapshot] = []
override func viewDidLoad() {
super.viewDidLoad()
db = Firestore.firestore()
tableView.dataSource = self
tableView.delegate = self
retrieveAllPosts()
getuserscores()
var AViewController: UIViewController = UIViewController()
var MyTabBarItem: UITabBarItem = UITabBarItem(title: nil, image: UIImage(named: "pencil")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal), selectedImage: UIImage(named: "pencil"))
AViewController.tabBarItem = MyTabBarItem
// Do any additional setup after loading the view.
// navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(handleLogout))
}
func getuserscores(){
let userRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid)
userRef.getDocument{(document, error) in
if let document = document, document.exists{
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
let l1 = document.get("l1") as! Int
let l2 = document.get("l2") as! Int
let l3 = document.get("l3") as! Int
let l4 = document.get("l4") as! Int
let newScores = Scores(_l1: l1, _l2: l2, _l3: l3, _l4: l4)
self.scores1.append(newScores)
}
self.tableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func retrieveAllPosts(){
let postsRef = Firestore.firestore().collection("posts").order(by: "timestamp", descending: true).limit(to: 50)
postsRef.getDocuments { (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 postcategory = data["postcategory"] as? String ?? ""
let postContent = data["postContent"] as? String ?? ""
let postAuthorProfilePicUrl = data["post_user_profile_pic_url"] as? String ?? ""
let postAuthorSpinnerC = data["post_author_spinnerC"] as? String
let newSourse = Post(_documentId: document.documentID, _username: username, _postTitle: postTitle, _postcategory: postcategory, _postContent: postContent, _postuserprofileImagUrl: postAuthorProfilePicUrl, _postAuthorSpinncerC: postAuthorSpinnerC)
self.posts.append(newSourse)
}
self.tableView.reloadData()
}
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableView.automaticDimension
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return scores1.count + posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 && scores1.count == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "SmileMiles") as! ScoresCellInHomeScreen
cell.set(scores: scores1[indexPath.row])
return cell
} else if posts.count > (indexPath.row - 1 ) {
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.btnComment.tag = indexPath.row - 1
cell.btnComment.addTarget(self, action: #selector(toComments(_:)), for: .touchUpInside)
cell.favoritebutton.tag = indexPath.row - 1
cell.favoritebutton.addTarget(self, action: #selector(favupdate(_:)), for: .touchUpInside)
cell.set(post: posts[indexPath.row - 1 ])
return cell
} else {
return UITableViewCell()
}
}
#objc func favupdate(_ sender: AnyObject) {
let commentbutton = sender as! UIButton
let post = posts[commentbutton.tag]
postKey = post._documentId // or what key value it is
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_gender": self.postAuthorGender,
// "post_author_dateOfBirth": self.dateOfBirth,
"post_author_spinnerC": self.postAuthorSpinnerC,
"post_author_fullname": self.postAuthorfullname,
"post_author_id": self.postAuthorId,
"post_author_username": self.postAuthorname,
"post_author_email": self.postAuthorEmail,
"postTitle": self.PostTitle,
"postcategory": self.postCategory,
"postContent": self.postContent,
// "post_timestamp": FieldValue.serverTimestamp(),
"post_user_profile_pic_url":self.postAuthorPicUrl,
"post_id": self.postKey
] as [String : Any]
userMarkRef.setData(postObject, merge: true) { (err) in
if let err = err {
print(err.localizedDescription)
}
print("Successfully set new user data")
}
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 {
return 150
}
else{
return UITableView.automaticDimension
}
}
#objc func toComments(_ sender: AnyObject) {
let commentbutton = sender as! UIButton
let post = posts[commentbutton.tag]
postKey = post._documentId // or what key value it is
print(postKey + "hello")
performSegue(withIdentifier: "toCommentsList", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "toCommentsList"){
var vc = segue.destination as! CommentListViewController
vc.postId = postKey
}
}
}
Do this in tableview cellForRowAt function before return cell:
cell.selectionStyle = .none
return cell
this will fix the issue

Index out of range error keeps crashing my app

I have a tableview loading data from firebase database. When i open my app the data does not populate. it crashes and throws the error index out of range. I am fairly new to xcode and would appreciate the help. i have been given recommendations on how to fix my code with regards to having multiple arrays but everyone that advices forget i'm new and does realize that i am pulling imageurls into my tableview too and dont know how to adopt their recommendations into my code. if i could get help getting passed this error that would be awesome.
import UIKit
import FirebaseAuth
import FirebaseDatabase
class EventsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var eventsRef: DatabaseReference?
var eventsDatabaseHandle:DatabaseHandle?
var eventsTitles = [String]()
var eventTimestamps = [String]()
var eventsLocations = [String]()
var eventsImages = [UIImage]()
#IBOutlet weak var addEventsButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
adminAuth()
eventsRef = Database.database().reference()
tableView.reloadData()
tableView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi)
tableView.delegate = self
tableView.dataSource = self
eventsDatabaseHandle = eventsRef?.child("Church Events").observe(.childAdded, with: { (snaphot) in
let eventPost = snaphot.value as! [String: Any]
self.eventTimestamps.append(eventPost["eventdate"] as! String)
self.eventsTitles.append(eventPost["eventtitle"] as! String)
self.eventsLocations.append(eventPost["eventlocation"] as! String)
let task = URLSession.shared.dataTask(with: URL(string: eventPost["ImageUrl"] as! String)!) {(data, response, error) in
if let image: UIImage = UIImage(data: data!) {
self.eventsImages.append(image)
}
}
task.resume()
self.tableView.reloadData()
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventsTitles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "events") as! EventsTableViewCell
// let image = eventsImages[indexPath.row]
cell.flyerImages.image? = eventsImages[indexPath.row] **<- index out of range**
cell.eventTitle.text! = eventsTitles[indexPath.row]
cell.eventDate.text! = eventTimestamps[indexPath.row]
cell.eventLocation.text! = eventsLocations[indexPath.row]
cell.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
return cell
}
func adminAuth() {
if (Auth.auth().currentUser!.displayName != "Neil Leon") {
self.addEventsButton.tintColor = UIColor.clear
self.addEventsButton.isEnabled = false
}
else{
self.addEventsButton.isEnabled = true
}
}
}``````
At the moment reloadData is called the image array is empty and causes the crash
Use a custom struct and reload the table view after the image data has been received
struct Event {
let title, timestamp, location : String
var image : UIImage?
}
var events = [Event]()
...
eventsDatabaseHandle = eventsRef?.child("Church Events").observe(.childAdded, with: { (snaphot) in
let eventPost = snaphot.value as! [String: Any]
let event = Event(title: eventPost["eventtitle"] as! String,
timestamp: eventPost["eventdate"] as! String,
location: eventPost["eventlocation"] as! String,
image: nil)
let task = URLSession.shared.dataTask(with: URL(string: eventPost["ImageUrl"] as! String)!) { data, _, error in
if let error = error {
print(error)
} else {
event.image = UIImage(data: data!)
DispatchQueue.main.async {
self.events.append(event)
self.tableView.reloadData()
}
}
}
task.resume()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return events.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "events", for: indexPath) as! EventsTableViewCell
let event = events[indexPath.row]
cell.flyerImages.image = event.image
cell.eventTitle.text = event.title
cell.eventDate.text = event.timestamp
cell.eventLocation.text = event.location
cell.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
return cell
}

My data from firebase database is not loading into my tableview

I have a tableview loading data from firebase database. When I open my app the data does not populate. when I create a new post I can see the tableview cells modifying like changed were made but the post doesn't populate. I can't figure it out.
import UIKit
import FirebaseAuth
import FirebaseDatabase
class EventsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var eventsRef: DatabaseReference?
var eventsDatabaseHandle:DatabaseHandle?
var eventsTitles = [String]()
var eventTimestamps = [String]()
var eventsLocations = [String]()
var eventsImages = [UIImage]()
#IBOutlet weak var addEventsButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
adminAuth()
eventsRef = Database.database().reference()
tableView.reloadData()
tableView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi)
tableView.delegate = self
tableView.dataSource = self
eventsDatabaseHandle = eventsRef?.child("Church Events").observe(.childAdded, with: { (snaphot) in
let eventPost = snaphot.value as! [String: Any]
self.eventTimestamps.append(eventPost["eventdate"] as! String)
self.eventsTitles.append(eventPost["eventtitle"] as! String)
self.eventsLocations.append(eventPost["eventlocation"] as! String)
let task = URLSession.shared.dataTask(with: URL(string: eventPost["ImageUrl"] as! String)!) {(data, response, error) in
if let image: UIImage = UIImage(data: data!) {
self.eventsImages.append(image)
}
}
self.tableView.reloadData()
task.resume()
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventsImages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "events") as! EventsTableViewCell
let image = eventsImages[indexPath.row]
cell.flyerImages.image! = image
cell.eventTitle.text! = eventsTitles[indexPath.row]
cell.eventDate.text! = eventTimestamps[indexPath.row]
cell.eventLocation.text! = eventsLocations[indexPath.row]
cell.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
tableView.reloadData()
return cell
}
func adminAuth() {
if (Auth.auth().currentUser!.displayName != "Neil Leon") {
self.addEventsButton.tintColor = UIColor.clear
self.addEventsButton.isEnabled = false
}
else{
self.addEventsButton.isEnabled = true
}
}
}
image of empty tableview
]
So the code below is not tested as I don't have firebase setup currently.
However, observing childAdded... the documentation says it will pass all of the current records in the database at first and will then just post new additions. So all you need to do is loop through them, setup your tableView data source and reload the table.
Rather than use multiple arrays for values I've created an array of ChurchEvent objects instead.
struct ChurchEvents {
let title: String
let location: String?
let date: Date?
let imageUrlString: String?
init(dict: [String: Any]) {
self.title = dict["title"] as String
self.location = dict["location"] as? String
// etc
}
}
var events = [ChurchEvents]()
eventsDatabaseHandle = eventsRef?.child("Church Events").observe(.childAdded, with: { snapshot in
let list = snapshot.value as? [[String : AnyObject]]
let newEvents = list.map { ChurchEvent(dict: $0) }
events.append(newEvents)
tableView.reloadData()
}
Other improvements you could make:
class EventsTableViewCell: UICollectionViewCell {
func configure(with event: ChurchEvent {
eventDate.text = event.date
eventTitle.text = event.title
eventLocation.text = event.location
// etc
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "events") as! EventsTableViewCell
let event = events[indexPath.row]
cell.configure(with: event)
return cell
}

table view cannot be displayed on device

I am developing iOS app where I want to display table content one my device.but unable fetch and display...but contents are being displayed on console view.
I am using json getmethod() to fetch the details
also using view controller and view table and swift language
import UIKit
class UpdateSheetManagementViewController:
UIViewController, UITableViewDelegate, UITableViewDataSource, WebserviceDelegate {
//var FinalArray = [[String:Any]]()
// class func instantiateFromStoryboard() -> UpdateSheetManagementViewController {
// let storyboard = UIStoryboard(name: "Management", bundle: nil)
// return storyboard.instantiateViewController(withIdentifier: String(describing: self)) as! UpdateSheetManagementViewController
// }
#IBOutlet weak var managementTableView: UITableView!
var controllerType : String!
var array = [[String : Any]]()
override func viewDidLoad() {
super.viewDidLoad()
title = controllerType
updatesheetWebserviceCall()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// updatesheetWebserviceCall()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 320.0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCell(withIdentifier: "UpdateSheetManagementTableViewCell", for: indexPath) as! UpdateSheetManagementTableViewCell
let cellIdentifier : String = "UpdateSheetManagementTableViewCell";
let cell : UpdateSheetManagementTableViewCell =
tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! UpdateSheetManagementTableViewCell
let dict = array[indexPath.section]
cell.classname.text = dict["Cls_Name"] as? String
cell.dateFrom.text = dict["Date_From"] as? String
cell.date_To.text = dict["Date_To"] as? String
cell.downloadButton.tag = indexPath.row
cell.downloadButton.addTarget(self, action: #selector(onDownloadButtonClicked(button:)), for: .touchUpInside)
return cell
}
func onDownloadButtonClicked(button : UIButton) {
let postion = button.tag
let data = array[postion]
let attachment = data["Attachment"] as? String
if(attachment != nil && attachment!.characters.count > 0){
let userid = UserDefaults.standard.string(forKey: USER_ID)
let finalString = "https://skillskool.mycit.co.in/PagesParentApp/Today-ClassNotes.aspx?FilePath=" + attachment! + "&UserId=" + userid! + "&PageName=UpdateSheet"
let url = URL(string: finalString)
if(url != nil){
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
}
}
}
func updatesheetWebserviceCall() {
let str = ""
let webClass = WebserviceClass()
webClass.delegate = self
webClass.fireRequest(functionName: "MgmtUpdateSheet.php", requestString: str, view: view)
}
func webserviceDidFinishWith(response: [String : Any], functionName: String) {
parseUpdateSheetWebservice(response: response)
}
func parseUpdateSheetWebservice(response : [String : Any]) {
let arr = response["homework"] as? [[String : Any]]
if(arr != nil){
// array.removeAll()
self.array.append(contentsOf: arr!)
// managementTableView.reloadData()
}
}
}
Add managementTableView.reloadData() after updating the data and make sure to set the delegate and datasource in either view controller or storyboard
Set tableview delegate and datasource in viewDidLoad and reload tableview in web service response.
// set tableview delegate and datasource in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
title = controllerType
managementTableView.dataSource = self
//managementTableView.delegate = self
updatesheetWebserviceCall()
}
// reload tableview upon web service response
func parseUpdateSheetWebservice(response : [String : Any]) {
let arr = response["homework"] as? [[String : Any]]
if(arr != nil){
// array.removeAll()
self.array.append(contentsOf: arr!)
self.managementTableView.reloadData()
/*
// or reload table using main queue, if you web service operation is in background queue
DispatchQueue.main.async {
self.managementTableView.reloadData()
}
*/
}
}
In the beginning, you need to set tableview dataSource and delegate and after loading data you also need to reload data.
self.managementTableView.delegate = self;
self.managementTableView.datasource = self;
Reload data:
self.array.append(contentsOf: arr!)
self.managementTableView.reloadData()
You have to set in viewDidLoad
managementTableView.dataSource = self
and un comment managementTableView.reloadData()
func parseUpdateSheetWebservice(response : [String : Any]) {
let arr = response["homework"] as? [[String : Any]]
if(arr != nil){
// array.removeAll()
self.array.append(contentsOf: arr!)
DispatchQueue.main.async {
managementTableView.reloadData() }
}
}
I think delegate and datasource connections are missed, please add the following code in viewDidLoad function:
self.managementTableView.delegate = self;
self.managementTableView.dataSource = self;

tableview not refreshing by using notificationcentre and tableview.reloaddata()

here is the code I use to refresh a tableview when I click a delete button on my custom tableview cell by using notificationcenter and tableview.reloaddata(). I have searched a bunch of other codes and i think my code looks fine. I don't know why it just doesn't refresh.
This is where my tableview is
override func viewDidLoad() {
super.viewDidLoad()
username = tempUser.username
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.sizeToFit()
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
get{(value) in
self.values = value
for ele in self.values{
if self.username != ele["username"] as! String{
}
}
}
self.tableView.reloadData()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(serviceBoard.methodhandlingTheNotificationEvent), name:"NotificationIdentifie‌​r", object: nil)
}
func methodhandlingTheNotificationEvent(){
tableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.resultSearchController.active && resultSearchController.searchBar.text != "") {
return self.filteredTableData.count
}
else {
return values.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as!postCell
let maindata = values[values.count-1-indexPath.row]
if (self.resultSearchController.active && resultSearchController.searchBar.text != "") {
// if (filteredTableData[indexPath.row].rangeOfString("###") == nil){
cell.postImg.image = UIImage(named:"tile_services")
cell.title.text = filteredTableData[indexPath.row]
cell.category.text = "SERVICES"
var price = String()
for i in values{
if (i["title"] as? String)! == filteredTableData[indexPath.row]{
price = (i["price"] as? String)!
cell.categories = "Services"
cell.username = i["username"] as! String
cell.prices = i["price"] as! String
cell.notes = i["notes"] as! String
cell.school = i["school"] as! String
}
}
cell.price.text = price
return cell
}
else {
if maindata["username"] as! String != username && username != "admin"{
cell.deleteBtn.hidden = true
}
else{
cell.categories = "Services"
cell.username = maindata["username"] as! String
cell.prices = maindata["price"] as! String
cell.notes = maindata["notes"] as! String
cell.school = maindata["school"] as! String
}
cell.postImg.image = UIImage(named:"tile_services")
cell.title.text = maindata["title"] as? String
cell.category.text = "SERVICES"
cell.price.text = maindata["price"] as? String
return cell
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("showPostT") as! showPostT
self.addChildViewController(popOverVC)
popOverVC.view.frame = self.view.frame
self.view.addSubview(popOverVC.view)
popOverVC.didMoveToParentViewController(self)
if (self.resultSearchController.active && resultSearchController.searchBar.text != "") {
for i in values{
if (i["title"] as? String)! == filteredTableData[indexPath.row]{
popOverVC.type.text = "SERVICE"
popOverVC.typeImg.image = UIImage(named:"tile_services")
popOverVC.item.text = "Service: \(i["title"] as! String)"
popOverVC.price.text = "Price: \(i["price"] as! String)"
popOverVC.notes.text = "Notes: \(i["notes"] as! String)"
popOverVC.comments.text = i["comments"] as? String
popOverVC.postUser.text = i["username"] as! String
popOverVC.notesStr = i["notes"] as! String
popOverVC.category = "service"
popOverVC.pricesStr = i["price"] as! String
if username == popOverVC.postUser.text!{
popOverVC.composeBtn.hidden = true
}
}
}
}
else{
let maindata = values[values.count-1-indexPath.row]
popOverVC.type.text = "SERVICE"
popOverVC.typeImg.image = UIImage(named:"tile_services")
popOverVC.item.text = "Service: \(maindata["title"] as! String)"
popOverVC.price.text = "Price: \(maindata["price"] as! String)"
popOverVC.notes.text = "Notes: \(maindata["notes"] as! String)"
popOverVC.comments.text = maindata["comments"] as? String
popOverVC.postUser.text = maindata["username"] as! String
popOverVC.notesStr = maindata["notes"] as! String
popOverVC.category = "service"
popOverVC.pricesStr = maindata["price"] as! String
if username == popOverVC.postUser.text!{
popOverVC.composeBtn.hidden = true
}
}
}
and this is my custom tableview cell
class postCell: UITableViewCell{
#IBOutlet weak var deleteBtn: UIButton!
#IBOutlet weak var postImg: UIImageView!
#IBOutlet weak var category: UILabel!
#IBOutlet weak var location: UILabel!
#IBOutlet weak var title: UILabel!
#IBOutlet weak var price: UILabel!
var prices = String()
var notes = String()
var comments = String()
var locations = String()
var categories = String()
var school = String()
var username = String()
var date = String()
#IBAction func deleteAction(sender: AnyObject) {
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.percyteng.com/orbit/deletePost.php")!)
request.HTTPMethod = "POST"
let postString = "name=\(username)&location=\(locations)&price=\(prices)&notes=\(notes)&school=\(school)&category=\(categories)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume(); NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifie‌​r", object: nil)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated:animated)
}
}
It looks like you are not updating the values property when you click on the "Delete" button.
func methodhandlingTheNotificationEvent(){
// you have to update the `values` array so that it doesn't contain the value you've just removed.
tableView.reloadData()
}
Try to reload table in viewDidAppear().
You have to update your data source before reloading tableview then only your tableview will affected otherwise you will always got old table.
I think maindata is main datasource in your cellforrowAtIndexpath. So you have to update or delete from your datasource and then you should reload data.

Resources