I'm building out a image feed that includes an image followed by a username label inside of a table view. For some reason, the cell images don't match the correct usernames. It almost seems that the images are downloaded in a different order than the usernames, but that can't be the case. Please help!
EDIT: After doing some console logging, I see that the images are downloaded and appended to the images array, in an different order than the usernames. BUT I don't know why, nor how to fix it.
import UIKit
class TrendingChallengeTableViewCell: UITableViewCell {
@IBOutlet var postImage: UIImageView!
@IBOutlet var postComment: UILabel!
override func prepareForReuse() {
super.prepareForReuse()
self.postImage.image = nil
self.postComment.text = ""
}
}
import UIKit
import Parse
var pressedChallenge: String?
class TrendingChallengeTableViewController: UITableViewController {
var images = [PFFile]()
var usernames = [String]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.hidesBackButton = true
let query = PFQuery(className: "Post")
query.whereKey("imageComment", equalTo: pressedChallenge!)
query.findObjectsInBackgroundWithBlock { (object, error) -> Void in
self.usernames.removeAll(keepCapacity: true)
self.images.removeAll(keepCapacity: true)
if let object = object {
for images in object {
self.images.append(images["imageFile"] as! PFFile)
let userQuery = PFUser.query()
userQuery?.whereKey("_id", equalTo: images["userId"])
userQuery?.findObjectsInBackgroundWithBlock({ (object, error) -> Void in
if let object = object {
for user in object {
self.usernames.append(user["username"] as! String)
self.tableView.reloadData()
}
}
})
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return usernames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let trendCell = tableView.dequeueReusableCellWithIdentifier("trendingCell", forIndexPath: indexPath) as! TrendingChallengeTableViewCell
trendCell.postComment.text = "\(usernames[indexPath.row]) completed the \(pressedChallenge!) challenge!"
images[indexPath.row].getDataInBackgroundWithBlock { (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
trendCell.postImage.image = downloadedImage
}
}
return trendCell
}
}