Search code examples
iosuitableviewswift3scrollscrollview

UITableView Scrolls To Undesired Index or Position


Basically the task is to load new API response as the user scrolls to down in UITableView without stopping user interaction and maintaining the current position (live feeds like Facebook and Instagram).

What I want to do is that parsing and then viewing Rest API's response in UITableView with custom cells.

The issue is that when the user scrolls to bottom the API call is made and table view scrolls to some other position where the user is.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

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


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

    let cell = tableView.dequeueReusableCell(withIdentifier: "xxxxx", for:indexPath) as! xxxxxxxx

    return cell;
}



func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    if scrollView == tableView {
        if ((scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height) {
            print("Scroll Ended")
            fetchDataFromApi()
        }
    }
}


func fetchDataFromApi() {

    let jsonUrlString = "xxxxxxx"


    guard let url = URL(string: jsonUrlString) else {
        return
    }

    print(url)

    URLSession.shared.dataTask(with: url) {(data,response,err) in

        guard let data = data else {
            return
        }
        do {
            let apiResponseData = try JSONDecoder().decode(ApiResponse.self, from: data)

            if apiResponseData.httpStatusCode == HttpStatusCode.OK {

                if let apiResponse = apiResponseData.data{
                    self.array.append(contentsOf: apiResponse)
                }


                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }

            }
            else {
                print("API Response Error : \(apiResponseData.httpStatusCode) \(apiResponseData.errorMessage)")
            }
        }catch let jsonErr {
            print("Serialization Error \(jsonErr)")
        }
        }.resume()
}}

Solution

  • It was because of dynamic cell sizes I was setting in table view