CustomTableView永远不会更新

时间:2017-04-25 14:04:36

标签: ios json uitableview swift3 xcode8

此代码假设从JSON对象获取数据然后用它更新表的行,所以我使用了(tableView.reloaddata)但它不起作用。

class history: UIViewController,UITableViewDataSource,UITableViewDelegate {
    var rec = [recs]()
    var delegate2 : historyViewControllerProtocol!
    var ID2 = [String]()
    var Amount2 = [String]()
    var Desc2 = [String]()
    var records:String = ""

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        reciptshistory(){ (boolValue) -> () in
            self.Loaddata()
            self.tableView.reloadData()
                   }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


    func reciptshistory(completion: @escaping (_ result: Bool)->())
    {

        var Buffer : String
        Buffer = "userID=" + userID

        print("intial///////////////////" + Buffer + "//////////////End")

        let url:NSURL = NSURL(string: "http://nh75.com.kw/old-soon/Paynet/recipthistory.php")!
        let session = URLSession.shared

        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

        let data = Buffer.data(using: String.Encoding.utf8)
        let task = session.uploadTask(with: request as URLRequest, from: data, completionHandler:
            {(data,response,error) in


                guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
                    print("error")
                    return
                }

                let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
                print(dataString as Any)
                self.records = dataString!;


                if(self.records == "X")
                {
                    print("No records");
                    completion (true)

                } else {
                    print (dataString! )
                    do {
                        // let data = dataString?.data(using: .utf8)
                        let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:AnyObject]
                        if let result = json["result"] as? [[String: AnyObject]] {
                            for blog in result {
                                if let iD = blog["id"] as? String {
                                    if let amount = blog["Amount"] as? String {
                                        if let desc = blog["Desc"] as? String {
                                            self.ID2.append(iD)
                                            self.Amount2.append(amount)
                                            self.Desc2.append(desc)
                                            //recipt.text = self.ID
                                            //print(ID , Amount , Desc)
                                        }
                                    }
                                }
                            }
                            completion (true)
                        }
                    }catch {
                        print("error serializing JSON: \(error)")
                    }
                }





        }


        );
        task.resume()
    }


    func Loaddata()
    {
         DispatchQueue.main.async {
     if(self.records == "X")
     {

                let alert = UIAlertController(
                    title: "No Records found",
                    message: "No records found for you",
                    preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: { (test) -> Void in
                    self.dismiss(animated: true, completion: nil)
                }))

                self.present(
                    alert,
                    animated: true,
                    completion: nil)




     }else{

        for L in 0..<self.ID2.count{
                self.rec += [recs(reciptsnum: self.ID2[L] , amount:self.Amount2[L] , descript: self.Desc2[L])!]
        }
        }
        }
        }





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



    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rec.count

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Table view cells are reused and should be dequeued using a cell identifier.
        let cellIdentifier = "RecTableViewCell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! RecTableViewCell
        // Fetches the appropriate meal for the data source layout.

        let recc = rec[(indexPath as NSIndexPath).row]
        cell.reciptnum.text = recc.reciptsnum
        cell.Amount.text = recc.amount
        cell.descript.text = recc.descript
        return cell

    }

每次我运行应用程序时,自定义tableview都是空的,请指教...... here is a screenshot of the app running

3 个答案:

答案 0 :(得分:1)

在我看来,您的控制器并未作为委托和数据源连接到您的表。如果你在故事板中将它设置为'UITableViewController'而不是'UIViewController'(和子类'history'作为UITableViewController),它应该自动连接。

您还可以使用以下代码连接:

tableView.delegate =自 tableView.datasource =自

但你仍然可能必须将子类化为UITableViewController而不是UIViewController。

答案 1 :(得分:0)

有些事情要尝试:

将TableView委托和数据源设置为自我

在故事板上设置单元格重用标识符

确保正在正确拉取数据,并且在重新加载表时数组不为空

答案 2 :(得分:0)

我更新了代码,因为@Gagan_IOS建议并且它工作得很好.....

ZIP

由于