0

I have ViewController in which I have UITableview and custom cell. My code is correct and I did delegate and datasource also. I have IBoutlets in tableViewCell also. I will see only empty lines nothing else, I don't see cellbackground colour also which is set in storyboard.

class HomeVC: UIViewController , UITableViewDataSource , UITableViewDelegate  {

@IBOutlet weak var profileImg: UIImageView!
@IBOutlet weak var fullnameLbl: UILabel!
@IBOutlet weak var emailLbl: UILabel!
@IBOutlet weak var usernameLbl: UILabel!
@IBOutlet weak var editprofileBtn: UIButton!

var tableData = [AnyObject]()
var username = String()

@IBOutlet var homeSwipe: UISwipeGestureRecognizer!
@IBOutlet weak var tableView: UITableView!
var pflegerId = String()

var weekday = Date().dayOfWeek()

@IBAction func swipe(_ sender: Any) {

}

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.delegate = self
    self.tableView.dataSource = self


   //Swipe gesture

     username = (user!["username"] as AnyObject).uppercased
    let fullname = user!["fullname"] as? String
    let email = user!["email"] as? String
   pflegerId = (user!["id"] as? String)!

    usernameLbl.text = username
    fullnameLbl.text = fullname
    emailLbl.text = email

    loadData(username : username)



}

func loadData(username : String) {


    let url = URL(string: "http:..")


    var request = URLRequest(url: url!)
    request.httpMethod = "POST"
    let body = "Id=\(pflegerId)"

    request.httpBody = body.data(using: .utf8)

    URLSession.shared.dataTask(with: request) { data, response, error in

        if error == nil {

            DispatchQueue.main.async(execute: {

                do{
                    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
                    print(json)


                    guard let parseJSON = json else {
                        print("")
                        return
                    }

                    guard let posts = parseJSON["posts"] as? [AnyObject] else{
                        print("error while parseJSON")
                        return
                    }


                    self.tableData = posts

                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }


                }catch {
                    //print("Caught an error: \(error)")
                    DispatchQueue.main.async(execute: {
                        let message = ""
                        appDelegate.infoView(message: message, color: colorSmoothRed)
                    })
                }
            })


        }else {
            //print("error: \(error)")
            DispatchQueue.main.async(execute: {
                let message = error!.localizedDescription
                appDelegate.infoView(message: message, color: colorSmoothRed)
            })

        }
        }.resume()

}





@IBAction func logout_click(_ sender: Any) {
    //alle Daten löschen
    UserDefaults.standard.removeObject(forKey: "parseJSON")
    UserDefaults.standard.synchronize()

    //jetzt wieder zur Login Ansicht wechseln.
    let loginvc = self.storyboard?.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
    self.present(loginvc, animated: true, completion: nil)


}


//TABLEVIEW

func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}

//Total number of Rows in Table
func tableView (_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    print(tableData.count)
    return tableData.count


}





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

    // Configure the cell...
    let tableData = self.tableData[indexPath.row]
    cell.patientNameLbl?.text = tableData["name"] as? String
    cell.addressLbl?.text = tableData["address"] as? String
    cell.timeLbl?.text = tableData["timing"] as? String

    return cell

}





func coolSwiped(_ swipe : UISwipeGestureRecognizer) {

    if swipe.direction == .right {
        DispatchQueue.main.async {
            appDelegate.swipeToTomorrow()
            self.tableView.reloadData()
        }
    }
    else if swipe.direction == .left {
        DispatchQueue.main.async {
            appDelegate.swipeToYesterday()
            self.tableView.reloadData()

        }
    }

}

}

SwiftUser
  • 29
  • 8
  • Check that your `tableData` array is not empty. – Nirav D Mar 22 '17 at 11:54
  • No it is not empty. It gets the values from server side.I have updated my code u can check it. – SwiftUser Mar 22 '17 at 11:57
  • 1
    For me some time it happened, that I implemented the protocols, but forgot to reference them in the storyboard. – mad_manny Mar 22 '17 at 11:57
  • Check the table outlet and Delegate is connected properly and then use the given code from my answer. – Aashish1aug Mar 22 '17 at 12:00
  • 2
    Have you checked in the debugger to see if your `UITableView` delegate methods are being called? And if they are, what the value for `numberOfRowsInSection` is when it returns? – Fahim Mar 22 '17 at 12:00
  • Shouldn't yesterdaysPatientListCell be a class instead? – Hapeki Mar 22 '17 at 12:05
  • @Fahim yes i did debug , numberOfRowsInSection = 2 – SwiftUser Mar 22 '17 at 12:05
  • @Hapeki yesterdaysPatientListCell is a UitableViewCell class, where I have declared IBoutlets. – SwiftUser Mar 22 '17 at 12:07
  • @ebby94 yes I did self.tableView.reloadData() in my loadData function once I finish with parsing data. – SwiftUser Mar 22 '17 at 12:09
  • @swiftUser reload your table on main thread in loadData() method.UI related task are done on main thread. – Tushar Sharma Mar 22 '17 at 12:09
  • You should have to reload table on Main Thread and test it for once by commenting your gesture code. – Aashish1aug Mar 22 '17 at 12:10
  • @all I did tried calling in main thread, still table is empty :-( – SwiftUser Mar 22 '17 at 12:14
  • Perhaps it might be time to provide a sample project so that we can see what might be going on in your project? At least, that's what helps me figure out what is going on - actually running the code which is misbehaving .... – Fahim Mar 22 '17 at 12:15
  • Can you print tableData.count in numberOfRowsInSection? – Hapeki Mar 22 '17 at 12:16
  • @Fahim how to send it as sample project? – SwiftUser Mar 22 '17 at 12:18
  • You can put it up on GitHub or upload to DropBox and post a link. Either should work ... – Fahim Mar 22 '17 at 12:19
  • The code in your question would *NOT* compile. Please post a _working_ sample of _relevant_ code. – Ashley Mills Mar 22 '17 at 12:19
  • Are you using storyboards or XIB ? In later case you need to register your cell class with table, as far as in obj C it's done. – Harish Pathak Mar 22 '17 at 12:21
  • @HarishPathak I use storyboard – SwiftUser Mar 22 '17 at 12:25
  • @AshleyMills edited my code..please check – SwiftUser Mar 22 '17 at 12:31
  • You have to check your storyboard to verify the Custom cell class name and Identifier value to "cell". May be you have miss something in StoryBoard. By the way you code is seem like correct. – Aashish1aug Mar 22 '17 at 12:32
  • @SwiftUser Try this... http://stackoverflow.com/questions/24833391/simple-uitableview-in-swift-unexpectedly-found-nil/26350795#26350795 – Harish Pathak Mar 22 '17 at 12:32
  • @Aashish1aug everything I again and again checked. I don't find any mistake. Looks like some where some silly mistake, which I am not able to track it. – SwiftUser Mar 22 '17 at 12:42
  • @SwiftUser As you say, it's probably something simple and might not even be in the code you've provided. If you can provide a working project which shows the issue you mean, I should be able to find it for you - but without an actual project, it's just guessing .... – Fahim Mar 22 '17 at 12:44

3 Answers3

0

I think you should specify rowheight for row.

ex.- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 60.0;
}

Mostly that resolved your problem.Let me know if not resolve.

Thanks Nirav Zalavadia

0

I have two questions for you:

  1. Can you hard code the aray and check it? This would eliminate the server issue.
  2. todaysPatientsListCell is this assigned to your custom cell in Storyboard?

Let me know if they helped.

-1

When you reload data after fetching the data, you need to do that in the main thread. So replace this line:

self.tableView.reloadData()

With the following:

DispatchQueue.main.async {
    self.tableView.reloadData()
}
Fahim
  • 3,466
  • 1
  • 12
  • 18