Search code examples
iosswiftuicollectionviewalamofire

How to fetch JSON data for UICollectionView with Alamofire, Swift 4


I have a UICollectionView which I'm trying to fill out with JSON data from server. For this purpose I'm using Alamofire library. In collection view we have two major methods:

First - Returns the number of cells in Collection

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return messagesArray!.count
}

Second - Returns the cell with content

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "chatMessage", for: indexPath) as! ChatMessageCell
    let messageObj = messagesArray![indexPath.item]
    let messageText = messageObj.userText
    cell.messageText.text = messageText
    return cell
}

For filling my collection I invoking my getChatMessages() method in viewDidLoad() method:

override func viewDidLoad() {
    super.viewDidLoad()

    setUpChatLogCollection()
    setupChatLogCollectionConstraints()
    getChatMessages()

}

So, I faced the problem - it seems like fetching server data with Alamofire starts working only after the Collection methods are done, so my collection doesn't get any data to show.

Guys, so how do you get data for your collections with Alamofire right?

I have tried viewWillAppear(), but it gave me the same result as viewDidLoad().


Solution

  • I assume that your data fetching methods are in the same view controller. So, once Alamofire returns with data, load it in your collection and call reloadData() method on collection view object.

    Ref: reloadData() on UICollectionView