I'm developing an iOS application that loads posts from a server into a UICollectionView. The collection view cell includes a UIImageView that is fixed to the bottom of the cell.
Whenever I start the application and the collection view loads, all the images do not load correctly but for the last image, which is the correct dimensions. All cells are being formatted the same way.
I have tried a multitude of solutions but nothing so far has worked.
What I suspect is happening is that the images have not finished loading before being set to the UIImageView of each cell (except for the last one in this case). This doesn't seem possible though as the cells are reloaded after getting a successful response..
This is my code for that particular function (using Alamofire)
func getAllPosts(){
let url = "\(Constants.baseURL)/posts/"
let parameters = ["user_id": "\(userProfile!.getId())"]
Alamofire.request(.POST, url, parameters: parameters, encoding: .JSON)
.validate(contentType: ["application/json"])
.responseString { response in
switch response.result {
case .Success:
var postsArray = Array<[String: AnyObject]>()
do {
let json = try NSJSONSerialization.JSONObjectWithData(response.data!, options: NSJSONReadingOptions.MutableContainers)
for post in json as! [AnyObject] {
postsArray.append(post as! [String: AnyObject])
}
//invert array of posts so that latest load first!
postsArray = postsArray.reverse()
} catch {
}
//convert json to Post objects and reload the view
self.initialisePosts(postsArray)
self.collectionView?.reloadData()
case .Failure(let error):
print(error)
}
}
}
All help is appreciated.
Edit: Below are the current constraints on the UIImageView
Edit 2: Here is the code for formatting the cells
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// get a reference to our postcell with no image
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifiers[0], forIndexPath: indexPath) as! PostCell
guard let _: Post? = posts[indexPath.row] else {
return cell
}
return configurePostCell(cell, post: posts[indexPath.row])!
}
func configurePostCell(cell: UICollectionViewCell, post: Post) -> PostCell?{
if let cell = cell as? PostCell {
cell.author.text = post.user_name
cell.date.text = formatter.stringFromDate(post.pub_date!)
cell.desc.text = post.desc
cell.layer.cornerRadius = 5 //set corner radius here
cell.advertImage.image = post.advert?.advert_image
return cell
}
return nil
}
Update: Using @Michael's Advice I have found that the Cell images are loading correctly..
but that the cell height is being mysteriously cropped by 50px..
Storyboard editor cell size
Cell size at run-time
This seems to be the issue but I have not found a solution yet.
Update: With two hours left on the bounty I have decided to award it to @Michael because his answer helped me to further investigation of my issue, which is still ongoing.