Проблема с индикатором активности при загрузке данных в UITableView

Я получаю запись с сервера с помощью php

Поскольку в настоящее время у меня есть 11 записей, поэтому я хочу, чтобы в начале я отображал только 6 записей, а оставшиеся следующие 5 записей будут отображаться, когда пользователь достиг последней ячейки при прокрутке. Итак, этот процесс находится в рабочей форме, но проблема в том, что во время работы он работает так быстро, что до достижения последней строки все записи уже отображаются при прокрутке, а индикатор активности просто анимируется в нижней части tableView.

Не знаю, в чем проблема.

Также я хочу, чтобы, когда пользователь достиг последней ячейки, индикатор активности начал анимацию при загрузке данных.

Вот мой код

import UIKit
import AlamofireImage

struct property{
let property_Id     : String
let propertyTitle   : String
let imageURL        : String
let user_Id         : String
let area            : String
let bed             : String
let unit            : String
let bath            : String
let price           : String
}
class searchRecordsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,favouriteButtonTableViewCellDelegate {

var y                           = 6
var m                           = 12
@IBOutlet weak var tableView    : UITableView!
var RESULT                      : [NSDictionary] = []
var myProperty                  = [property]()
var myPropertyCopy              = [property]()

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

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

//MARK: Getting dictionary data from previous controller

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    self.navigationItem.title = "Results"
    self.navigationController?.navigationBar.tintColor = UIColor.black

    //MARK: Getting dictionary data from previous controller
    for item in RESULT  {

        let propertyInfo = property(property_Id: String(item["propertyId"]! as! Int), propertyTitle: item["propertyTitle"]! as! String, imageURL: item["imagePath"]! as! String, user_Id: String(item["userId"]! as! Int), area: item["area"]! as! String, bed: item["bed"]! as! String, unit: item["unit"]! as! String, bath: item["bath"]! as! String, price: item["price"]! as! String )

        myProperty.append(propertyInfo)

    }
    //MARK: Inserting first 6 records in Array
    for i in 0 ..< 6 {
        if !(myProperty.indices.contains(i)) {
            break
        }
        myPropertyCopy.append(myProperty[i])

    }

}


func downloadImage(imagePath : String, theIMAGEVIEW : UIImageView) {
    let myUrl = URL(string: URL_IP+imagePath);

    //MARK: AlamofireImage to download the image
    theIMAGEVIEW.af_setImage(withURL: myUrl!, placeholderImage: #imageLiteral(resourceName: "addProperty"), filter: nil, progress: nil, runImageTransitionIfCached: true, completion: nil)
}

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

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

    let property = myPropertyCopy[indexPath.row]
    cell.area.text = property.area+" "+property.unit
    if property.bath == ""{
        cell.bath.text = property.bath
    }
    else{
        cell.bath.text = property.bath+" Baths"
    }
    if property.bed == ""{
        cell.bed.text = property.bed
    }
    else{
        cell.bed.text = property.bed+" Baths"
    }
    cell.propertyTitle.text = property.propertyTitle
    cell.price.text = convertAMOUNT(price : property.price)
    downloadImage(imagePath: property.imageURL, theIMAGEVIEW: cell.myImageView)
    //----
    cell.delegate = self

    return cell
}


func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    if myPropertyCopy.count != myProperty.count{
        let lastRow = myPropertyCopy.count - 1
        if indexPath.row == lastRow {
            let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
            spinner.startAnimating()
            spinner.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: tableView.bounds.width, height: CGFloat(44))

            self.tableView.tableFooterView = spinner
            self.tableView.tableFooterView?.isHidden = false
            moreData()

        }

    }
}

func moreData(){

    for i in y ..< m {
        if !(myProperty.indices.contains(i)) {

            break

        }
        myPropertyCopy.append(myProperty[i])

    }
        y = y + 10
        m = m + 10
        self.tableView.reloadData()

}



}

в настоящее время мой TableView выглядит как См. вывод здесь

Заранее спасибо.


person Ahtazaz    schedule 23.05.2018    source источник
comment
AnyOne здесь, помогите мне, пожалуйста   -  person Ahtazaz    schedule 24.05.2018
comment
если весь результат загружен, зачем снова разделять   -  person Justin Mathews    schedule 24.05.2018
comment
из-за того, что с сервера есть как минимум от 50 до 100 записей одновременно, я не хочу показывать сразу, потому что это странно, поэтому я хочу отображать фрагменты по 25, и когда пользователь достиг последней ячейки во время прокрутки, запускается индикатор активности анимировать, а затем загрузить следующие 25   -  person Ahtazaz    schedule 24.05.2018
comment
U показывает счетчик в нижнем колонтитуле каждый раз, когда нижний колонтитул отображается справа .. как только вы получаете следующие заданные записи .. анимация счетчика u отключите или скрыть нижний колонтитул   -  person Justin Mathews    schedule 24.05.2018
comment
Спасибо, я только что закончил :)   -  person Ahtazaz    schedule 24.05.2018
comment
Благодаря вашей помощи я получил это :)   -  person Ahtazaz    schedule 24.05.2018


Ответы (1)


После долгой практики я решил свою проблему, я только что добавил функцию делегата UIScrollView для проверки, достиг ли пользователь последней ячейки, затем запустите activityIndicator в течение 3 секунд, а затем загрузите данные и все.

Поскольку у меня очень мало данных, я начинаю использовать UIactivityIndicator за 3 секунды до получения данных.

 func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {

    // UITableView only moves in one direction, y axis
    let currentOffset = scrollView.contentOffset.y
    let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height

    if maximumOffset - currentOffset <= 10.0 {
        let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)

        if myPropertyCopy.count != myProperty.count {

            //print("this is the last cell")

            spinner.startAnimating()
            spinner.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: tableView.bounds.width, height: CGFloat(44))
            spinner.hidesWhenStopped = true
            self.tableView.tableFooterView = spinner
            self.tableView.tableFooterView?.isHidden = false

            DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                //MARK: Loading more data
                self.moreData()

            }

        }
        else{
            self.tableView.tableFooterView?.isHidden = true
            spinner.stopAnimating()
        }
    }

}
person Ahtazaz    schedule 24.05.2018