首页 > 解决方案 > TableView 不显示数据?

问题描述

tableView的没有显示数据。我正在通过 api 获取数据并将其保存到带有初始化程序的单独类中。但它并没有显示在tableView. 如何解决这个问题。我是 iOS 新手。我知道某处只有一行代码问题。

viewDidLoad我在方法中调用 api 。

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)

        //fetch all expected visitor data
        self.apiExpectedVisitor(strURL: urlViewExpectedVisitors)
        self.expectedTableView.reloadData()
    }

API方法的功能

func apiExpectedVisitor(strURL: String)
    {
        fetchedExpectedData = []

        //URL
        let myURL = URL(string: strURL)

        //URL Request
        let request = NSMutableURLRequest(url: myURL!)
        request.httpMethod = "GET"
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        let token = "Bearer " + strToken
        request.addValue(token, forHTTPHeaderField: "Authorization")

        let postTask = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
            print(response!)

            guard error == nil else {
                return
            }

            guard let data = data else {
                return
            }

            do {
                //create json object from data
                if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: [Any]] {
                    print("POST Method :\(json)")

                    DispatchQueue.main.async {

                        for expectedVisitors in json["expected_visitors"]!
                        {
                            let eachData = expectedVisitors as! [String: Any]

                            let id = eachData["id"] as! Int
                            let name = "\(String(describing: eachData["name"]))"
                            let email = "\(String(describing: eachData["email"]))"
                            let phone = eachData["phone"] as! String
                            let verification_code = "\(String(describing: eachData["expected_visitor_verification_code"]))"
                            let qr_code = eachData["expected_visitor_qr_code"] as? String
                            let isVisited = eachData["is_visited"] as! Int
                            let company_id = eachData["company_id"] as! Int
                            let purpose = "\(String(describing: eachData["purpose"]))"
                            let meeting_date = eachData["meeting_date"] as! String
                            let meeting_time = eachData["meeting_time"] as! String
                            let created_at = eachData["created_at"] as! String
                            let updated_at = eachData["updated_at"] as! String

                            //Date.formatter(createdDate: createdDate)

                            if let department_id = eachData["department_id"] as? Int, let employee_id = eachData["employee_id"] as? Int, let location_id = eachData["location_id"] as? Int, let image = eachData["image"] as? String, let duration = eachData["duration"] as? String {

                                fetchedExpectedData.append(FetchedAllExpectedVisitors.init(id: id, name: name, email: email, phone: phone, department_id: department_id, employee_id: employee_id, location_id: location_id, image: image, verification_code: verification_code, qr_code: qr_code!, isVisited: isVisited, company_id: company_id, purpose: purpose, meeting_date: meeting_date, meeting_time: meeting_time, duration: duration, created_at: created_at, updated_at: updated_at))

                                self.expectedTableView.reloadData()
                            }
                        }
                    }

                }
            } catch let error {
                print(error.localizedDescription)
            }
        }
        postTask.resume()

    }

TableView DataSourceDelegate方法

func numberOfSections(in tableView: UITableView) -> Int {
        return fetchedExpectedData.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

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

        cell.lblDate.text = fetchedExpectedData[indexPath.section].created_at
        cell.lblVisName.text = fetchedExpectedData[indexPath.section].name
        print(fetchedExpectedData[indexPath.section].name)

        for i in 0..<fetchedDepttData.count {

            let department_id = fetchedDepttData[i].depttID
            if fetchedExpectedData[indexPath.section].department_id == department_id
            {
                cell.lblDeptt.text = fetchedDepttData[i].depttName
            }
        }

        for i in 0..<fetchedEmployeeData.count {

            let employee_id = fetchedEmployeeData[i].empID
            if fetchedExpectedData[indexPath.section].employee_id == employee_id
            {
                cell.lblEmpName.text = fetchedEmployeeData[i].name
            }
        }

        return cell
    }

标签: iosswiftapiuitableview

解决方案


只需在 viewDidLoad 中添加以下代码

expectedTableView.delegate = self
expectedTableView.datasource = self

还要检查你是否在控制器的启动中设置了 UITableViewDelegate 、 UITableViewDataSource

class Yourviewcontrollername: UIViewController,UITableViewDelegate,UITableViewDataSource
{
    //Rest of the code
}

还要在所有委托方法中放置断点,看看是否有任何问题。


推荐阅读