-1

I am working on Chat application. I have a View Controller to display the messages in a tableview. On selecting a particular chat I will fetch 12 recent message & reload the table and scroll it to bottom so that user can see the recent message(index 11). As user starts scrolling up (as he reaches to 0th index) I need to fetch the history through a web service and display it on UI smoothly in the same order.

Code for displaying the cell

cell = STBubbleTableViewCell.init(style: .Subtitle, reuseIdentifier: cellIdentifier)
cell.backgroundColor = self.chatTableView?.backgroundColor
cell.selectionStyle = .None
cell.dataSource = self
cell.delegate = self

let chat = chatMessages[indexPath.row]

cell.textLabel?.font = UIFont.systemFontOfSize(14.0)
cell.textLabel?.text = chat.message
if(self.isGroupChat)
{
    cell.detailTextLabel?.text = NSString.init(format: "%@ %@", chat.authorName, chat.messageDate.toShortTimeString()) as String
}
else
{
    cell.detailTextLabel?.text = chat.messageDate.toShortTimeString()
}

cell.authorType = chat.authorType == 0 ? AuthorType.STBubbleTableViewCellAuthorTypeSelf : AuthorType.STBubbleTableViewCellAuthorTypeOther

cell.bubbleColor = chat.bubbleType == 0 ? BubbleColor.STBubbleTableViewCellBubbleColorGreen : BubbleColor.STBubbleTableViewCellBubbleColorGray

Code for fetching chat history

func scrollViewWillBeginDragging(scrollView: UIScrollView) {

    pointNow = scrollView.contentOffset
}

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

    if (scrollView.contentOffset.y < pointNow.y)
    {
        self.fetchChatHistory()
    }
}

self.fetchChatHistory is getting called multiple times. How to avoid this multiple calls?

Bista
  • 7,689
  • 3
  • 24
  • 52

1 Answers1

0

Using scrollViewWillBeginDragging and scrollViewDidEndDragging calls, you call fetching on each scroll, whatever the user has not reached the end of the table. Instead you need to implement tableview infinite scrolling:

give it a look: UITableView infinite scrolling

Community
  • 1
  • 1
iGenio
  • 379
  • 1
  • 6