I have success working tableview with json parsing codes.But may have 1000 more item so need pagination when scrolling bottom side. I dont know how can i do this my codes under below. For objective-c have a lot of example but for swift i didnt find working example. Im waiting your helps. I think will be help too many people. Thank you !
import UIKit class ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate { let kSuccessTitle = "Congratulations" let kErrorTitle = "Connection error" let kNoticeTitle = "Notice" let kWarningTitle = "Warning" let kInfoTitle = "Info" let kSubtitle = "You've just displayed this awesome Pop Up View" @IBOutlet weak var myTableView: UITableView! @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView! var privateList = [String]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) loadItems() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } internal func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return privateList.count } internal func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:myCell = tableView.dequeueReusableCellWithIdentifier("myCell") as! myCell cell.titleLabel.text = privateList[indexPath.row] return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete){ print(indexPath.row) let alert = SCLAlertView() alert.addButton("Hayır"){ } alert.addButton("Evet") { self.myTableView.beginUpdates() self.privateList.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left) print("Silindi") self.myTableView.endUpdates() self.loadItems() } alert.showSuccess(kSuccessTitle, subTitle: kSubtitle) } } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // the cells you would like the actions to appear needs to be editable return true } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "Detail") { let destinationView = segue.destinationViewController as! DetailViewController if let indexPath = myTableView.indexPathForCell(sender as! UITableViewCell) { destinationView.privateLista = privateList[indexPath.row] } } } internal func tableView(tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat { return 0.0 } func loadItems() { loadItemsNow("privateList") } func loadItemsNow(listType:String){ myActivityIndicator.startAnimating() let listUrlString = "http://bla.com/json2.php?listType=" + listType + "&t=" + NSUUID().UUIDString let myUrl = NSURL(string: listUrlString); let request = NSMutableURLRequest(URL:myUrl!); request.HTTPMethod = "GET"; let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in if error != nil { print(error!.localizedDescription) dispatch_async(dispatch_get_main_queue(),{ self.myActivityIndicator.stopAnimating() }) return } do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray if let parseJSON = json { self.privateList = parseJSON as! [String] } } catch { print(error) } dispatch_async(dispatch_get_main_queue(),{ self.myActivityIndicator.stopAnimating() self.myTableView.reloadData() }) } task.resume() } }
Setting up for pagination in swift Let's create an Xcode project, add a table view in the Main storyboard. Create TableViewCell and Xib. After that, register TableViewCell and assign delegate and dataSource. Your TableViewCell.
Overview. Table views in iOS display rows of vertically scrolling content in a single column. Each row in the table contains one piece of your app's content. For example, the Contacts app displays the name of each contact in a separate row, and the main page of the Settings app displays the available groups of settings ...
For that you need to have server side change also.
Server will accept fromIndex
and batchSize
in the API
url as query param.
let listUrlString = "http://bla.com/json2.php?listType=" + listType + "&t=" + NSUUID().UUIDString + "&batchSize=" + batchSize + "&fromIndex=" + fromIndex
In the server response, there will be an extra key totalItems
. This will be used to identify all items are received or not. An array or items fromIndex
to batchSize
number of items.
In the app side
First loadItem()
will be called with fromIndex = 0
and batchSize = 20
(for example in viewDidLoad()
or viewWillAppear
). removeAll items from privateList
array before calling loadItem()
for the first time
Server returns an array of first 20 items and totalItems
total number of items in the server.
Append the 20 items in privateList
array and reload tableView
In tableView:cellForRowAtIndexPath
method check if the cell is the last cell. And check if totalItems
(form server) is greater than privateList.count
. That means there are more items in the server to load
if indexPath.row == privateList.count - 1 { // last cell if totalItems > privateList.count { // more items to fetch loadItem() // increment `fromIndex` by 20 before server call } }
Question: where is refresh ? will be scrolling ?
Refresh after appending new items in the array when server response received. (step 3)
Scrolling will trigger tableView:cellForRowAtIndexPath
for every cell when user scrolls. Code is checking if it is the last cell and fetch remaining items. (step 4)
Sample project added:
https://github.com/rishi420/TableViewPaging
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With