Append table content, pagination

Hey All,


I have a table which i fill using a json request. On scroll a new request is done and new items get loaded. I would like these new items to be placed underneath the current items. My current code just refreshes the tableview thus deleting the current content.


Basicly i first load a few results in my table. on scroll i send another json request which gives me a few new results. I want to load these results inside the tableview. How can i keep the first results visible inside my table? A reload just shows the last request, this is because mydata3 is overwritten. How can i append the data inside mydata3 or can i achieve the same result another way?


I thought i would be able to fix this the following way but this gives me an error:

Cannot convert value of type '[SearchController.MyTableCell]' to expected argument type 'SearchController.MyTableCell'


var mydata4(self.mydata3)

self.mydata3 = response.resultcomp.map { value in
                    MyTableCell(
                        comp: value.comp,
                        comments: value.comments,
                        staravg: value.staravg,
                        maxkm: value.maxkm,
                        firstname: value.firstname,
                        compid: value.compid,
                        lastname: value.lastname,
                        createdon: value.createdon,
                        city: value.city,
                        functions: value.functions,
                        user: value.user,
                        version: value.version,
                        picture: value.picture,
                        xrefid: value.xrefid
                    )   
                }

mydata4.append(mydata3)



import Foundation
import UIKit

class ResultsComp: Codable {
    let resultcomp: [Resultcomp]
  
    init(resultcomp: [Resultcomp]) {
        self.resultcomp = resultcomp
    }
}


class Resultcomp: Codable {
    let staravg, maxkm, firstname, compid: String
    let lastname, comments, createdon, city: String
    let functions, user, comp, picture, version: String
    let xrefid: String
  
    init(staravg: String, maxkm: String, firstname: String, compid: String, lastname: String, comments: String, createdon: String, city: String, functions: String, user: String, comp: String, picture: String, version: String, xrefid: String) {
        self.staravg = staravg
        self.maxkm = maxkm
        self.firstname = firstname
        self.compid = compid
        self.lastname = lastname
        self.comments = comments
        self.createdon = createdon
        self.city = city
        self.functions = functions
        self.user = user
        self.comp = comp
        self.picture = picture
        self.version = version
        self.xrefid = xrefid
    }
}

class SearchController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
  
    var myVar:String = ""
  
  
    struct MyTableCell {
        let comp: String?
        let comments: String?
        let staravg: String?
        let maxkm: String?
        let firstname: String?
        let compid: String?
        let lastname: String?
        let createdon: String?
        let city: String?
        let functions: String?
        let user: String?
        let version: String?
        let picture: String?
        let xrefid: String?
    }
  
    var mydata3 = [MyTableCell]()
    var mycellID3 = "mycellID3"
  
  
    var data2: [AnyObject] = []
    var data: [AnyObject] = []
  
    lazy var scrollView: UIScrollView = {
        let view = UIScrollView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.contentSize.height = 1200
        view.backgroundColor = UIColor.white
      
        return view
    }()
  
  
    let mainMenu: UIButton = {
        let image = UIImage(named: "menu.PNG")
        let l = UIButton(type: .system)
        l.addTarget(self ,action: #selector(openMenu), for: .touchUpInside)
        l.setBackgroundImage(image, for: .normal)
      
      
        return l
      
    }()
  
  
  
    let categorieLabel: UILabel = {
      
        let t = UILabel()
      
        t.font = UIFont.boldSystemFont(ofSize: 24.0)
      
        t.textColor = yellowBanner
        return t
      
    }()
  
  
    let categorieDropdown: UITextView = {
      
        let t = UITextView()
      
        t.font = UIFont.boldSystemFont(ofSize: 16.0)
        t.backgroundColor = orangeBanner
        t.textColor = UIColor.white

        t.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 5);
        return t
    }()

    let categorieDropdown2: UITextView = {
      
        let t = UITextView()
        t.text = "Subcategorie"
        t.font = UIFont.boldSystemFont(ofSize: 16.0)
        t.backgroundColor = .white
        t.textColor = UIColor.black
        t.layer.borderWidth = 1.0;
        t.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 5);

        return t
    }()
  
  
    let filterButton: UIButton = {
      
        let h = UIButton()
        h.setTitle("Kies meer filters > ", for: .normal)
        h.setTitleColor(UIColor.black, for: .normal)
        h.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left
        h.titleLabel?.font = h.titleLabel?.font.withSize(24)
 
        return h
      
    }()
  
    let underFilter=UIView()

    var picker = UIPickerView()
    var picker2 = UIPickerView()

    let comptable2: UITableView = {
      
        let m = UITableView()
        m.backgroundColor = UIColor.white
      
        m.separatorStyle = .none
        return m
      
    }()
  

    var isDataLoading:Bool=false
    var pageNo:Int=1
    var limit:Int=5
    var offset:Int=0 //pageNo*limit
    var didEndReached:Bool=false
  
    override func viewDidLoad() {
        super.viewDidLoad()


        setupScrollView()
        view.backgroundColor = .white
      
      
        picker.delegate = self
        picker.dataSource = self
        picker2.delegate = self
        picker2.dataSource = self
      
        categorieDropdown.inputView = picker
        categorieDropdown2.inputView = picker2
      
      
        comptable2.rowHeight = UITableView.automaticDimension
        comptable2.estimatedRowHeight = 200
      
        comptable2.register(SearchCell.self, forCellReuseIdentifier: mycellID3)
        comptable2.delegate = self
        comptable2.dataSource = self
      



        DispatchQueue.main.async
            {
              
                self.categorieLabel.text = self.myVar
                self.categorieDropdown.text = self.myVar
              
              
        }
      
      
        let myUrl = URL(string: "https://myurl/myurl");
      
        var request = URLRequest(url:myUrl!)
      
        request.httpMethod = "POST"// Compose a query string
      
        let accessToken: String? = KeychainWrapper.standard.string(forKey: "token")
        let userId: String? = KeychainWrapper.standard.string(forKey: "id")
      
      
        let postString = "userId=\(userId!)&token=\(accessToken!)&pages=1";
      
        request.httpBody = postString.data(using: String.Encoding.utf8);
      
        let task = URLSession.shared.dataTask(with: request) { (data3: Data?, response: URLResponse?, error: Error?) in
          
            if error != nil
            {
                print("error=\(String(describing: error))")
                return
            }

            do {
                let json = try JSONSerialization.jsonObject(with: data3!, options: .mutableContainers) as? NSDictionary
            
                let test = "yes"
                let test2 = json!["showmore"]! as! String

                if test2 == test {

                let decoder = JSONDecoder()
                let response = try decoder.decode(ResultsComp.self, from: data3!)
              
                self.mydata3 = response.resultcomp.map { value in
                    MyTableCell(
                        comp: value.comp,
                        comments: value.comments,
                        staravg: value.staravg,
                        maxkm: value.maxkm,
                        firstname: value.firstname,
                        compid: value.compid,
                        lastname: value.lastname,
                        createdon: value.createdon,
                        city: value.city,
                        functions: value.functions,
                        user: value.user,
                        version: value.version,
                        picture: value.picture,
                        xrefid: value.xrefid
                    )    
                }
 
              
                DispatchQueue.main.async
                    {
   
                        self.comptable2.reloadData()
       
                    }}
              
            } catch {
                print(error)
            }
        }
      
        task.resume()
    }
  
    private func setupScrollView(){
        view.addSubview(scrollView)
      
      
        scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        scrollView.keyboardDismissMode = .onDrag
        scrollView.isScrollEnabled = true
   
        // Do any additional setup after loading the view
      
        let imageView = UIImageView(frame: CGRect(x: 10, y: 5, width: 150, height: 50))
        imageView.image = UIImage(named: "main.PNG")
      
        scrollView.addSubview(imageView)
        scrollView.addSubview(mainMenu)
      
        mainMenu.translatesAutoresizingMaskIntoConstraints = false
        mainMenu.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 5).isActive = true
        mainMenu.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -16).isActive = true
        mainMenu.heightAnchor.constraint(equalToConstant: 50).isActive = true
        mainMenu.widthAnchor.constraint(equalToConstant: 50).isActive = true
      
      
        view.addSubview(categorieLabel)
      
        categorieLabel.translatesAutoresizingMaskIntoConstraints = false
        categorieLabel.topAnchor.constraint(equalTo: mainMenu.bottomAnchor, constant: 15).isActive = true
        categorieLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 16).isActive = true
        categorieLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -16).isActive = true
        categorieLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
      
      
        view.addSubview(categorieDropdown)
      
        categorieDropdown.translatesAutoresizingMaskIntoConstraints = false
        categorieDropdown.topAnchor.constraint(equalTo: categorieLabel.bottomAnchor, constant: 15).isActive = true
        categorieDropdown.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 16).isActive = true
        categorieDropdown.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -16).isActive = true
        categorieDropdown.heightAnchor.constraint(equalToConstant: 50).isActive = true
      
        view.addSubview(categorieDropdown2)
      
        categorieDropdown2.translatesAutoresizingMaskIntoConstraints = false
        categorieDropdown2.topAnchor.constraint(equalTo: categorieDropdown.bottomAnchor, constant: 15).isActive = true
        categorieDropdown2.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 16).isActive = true
        categorieDropdown2.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -16).isActive = true
        categorieDropdown2.heightAnchor.constraint(equalToConstant: 50).isActive = true
      
        view.addSubview(filterButton)
      
        filterButton.translatesAutoresizingMaskIntoConstraints = false
        filterButton.topAnchor.constraint(equalTo: categorieDropdown2.bottomAnchor, constant: 15).isActive = true
        filterButton.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 16).isActive = true
        filterButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -16).isActive = true
        filterButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
      
      
        view.addSubview(underFilter)
      
        underFilter.translatesAutoresizingMaskIntoConstraints = false
      
        underFilter.topAnchor.constraint(equalTo: filterButton.bottomAnchor, constant: 15).isActive = true
        underFilter.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 16).isActive = true
        underFilter.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -16).isActive = true
        underFilter.heightAnchor.constraint(equalToConstant: 2).isActive = true
      
        underFilter.backgroundColor=grayBanner
      
        // Add rounded corners to UIView
        underFilter.layer.cornerRadius=0
      
      
        view.addSubview(comptable2)
      
        comptable2.translatesAutoresizingMaskIntoConstraints = false
      
        comptable2.topAnchor.constraint(equalTo: underFilter.bottomAnchor, constant: 15).isActive = true
        comptable2.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 16).isActive = true
        comptable2.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -16).isActive = true
        comptable2.heightAnchor.constraint(equalToConstant: 580).isActive = true
      
    }
  
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
      
        print("scrollViewWillBeginDragging")
        isDataLoading = false

    }
 
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
      
        let myUrl = URL(string: "https://myurl/myurl.php");
      
        var request = URLRequest(url:myUrl!)
      
        request.httpMethod = "POST"// Compose a query string
      
        let accessToken: String? = KeychainWrapper.standard.string(forKey: "token")
        let userId: String? = KeychainWrapper.standard.string(forKey: "id")
      
      
        let postString = "userId=\(userId!)&token=\(accessToken!)&pages=\(pageNo)";
      
        request.httpBody = postString.data(using: String.Encoding.utf8);
      
        let task = URLSession.shared.dataTask(with: request) { (data3: Data?, response: URLResponse?, error: Error?) in
          
            if error != nil
            {
                print("error=\(String(describing: error))")
                return
            }
  
            do {
                let json = try JSONSerialization.jsonObject(with: data3!, options: .mutableContainers) as? NSDictionary
              
                let test = "yes"
                let test2 = json!["showmore"]! as! String

              
                if test2 == test {
                  
                let decoder = JSONDecoder()
                let response = try decoder.decode(ResultsComp.self, from: data3!)

                    var mydata4 = self.mydata3
                  
                    self.mydata3 = response.resultcomp.map { value in
                    MyTableCell(
                        comp: value.comp,
                        comments: value.comments,
                        staravg: value.staravg,
                        maxkm: value.maxkm,
                        firstname: value.firstname,
                        compid: value.compid,
                        lastname: value.lastname,
                        createdon: value.createdon,
                        city: value.city,
                        functions: value.functions,
                        user: value.user,
                        version: value.version,
                        picture: value.picture,
                        xrefid: value.xrefid
                      
                    )

                }

                DispatchQueue.main.async
                    { 
                       self.comptable2.reloadData()         
         }
                }
            } catch {
                print(error)
            }
        }

        task.resume()
    }
    //Pagination
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
      
        print("scrollViewDidEndDragging")
        if ((comptable2.contentOffset.y + comptable2.frame.size.height) >= comptable2.contentSize.height)
        {
            if !isDataLoading{
                isDataLoading = true
                self.pageNo=self.pageNo+1
            }
        }
    }
  
    @objc func openMenu(){
      
        let menu = MenuController()
        present(menu, animated: true, completion: nil)
    }
  
  
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return mydata3.count
    }
  
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let mycell = self.comptable2.dequeueReusableCell(withIdentifier: mycellID3) as! SearchCell

        mycell.functions = mydata3[indexPath.row].functions!
        mycell.comments = mydata3[indexPath.row].comments!
        mycell.comp = mydata3[indexPath.row].comp!
        mycell.picture = mydata3[indexPath.row].picture!
        mycell.firstname = mydata3[indexPath.row].firstname!
        mycell.lastname = mydata3[indexPath.row].lastname!

        return mycell
    }
  
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        let a: Int! = Int(mydata3[indexPath.row].xrefid!)

        let myVar = "\(a!)"
        let test = AdvancedDescription()
        test.myVar = myVar
        present(test, animated: true, completion: nil)

    }
  
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
  
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
      
        if pickerView == picker {
          
            return data.count
          
        }else{
          
            return data2.count
        }
    }
  
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
      
        if pickerView == picker {
            categorieDropdown.text = " \(data[row] as! String)"
            categorieDropdown2.text = "Maak een selectie"
          
            let myvar =  "https://gipaa.nl/app/comp_json2.php?comp=\(categorieDropdown.text!)"
            let escapedAddress = myvar.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
            let url = NSURL(string: escapedAddress!)
          
            let data2 = NSData(contentsOf: url! as URL)
            var tmpValues = try! JSONSerialization.jsonObject(with: data2! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
            tmpValues = tmpValues.reversed() as NSArray
            reloadInputViews()

            self.data2.removeAll()
            for candidate in tmpValues {
                if let cdict = candidate as? NSDictionary {

                    //fullName is the column name in sql/json
                    let names = cdict["name"]
                    self.data2.append(names! as AnyObject)
                }
            }
        }else {
            categorieDropdown2.text = data2[row] as? String
        }
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView == picker {
            return data[row] as? String
        }else{
            return data2[row] as? String
        }
    }

Accepted Reply

The tableView is just the display.


Data should be stored in an array ; when you get more data, append to this array and call for reload tableView.


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { }


will read the array and put the content in cells.

Replies

The tableView is just the display.


Data should be stored in an array ; when you get more data, append to this array and call for reload tableView.


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { }


will read the array and put the content in cells.