JVS
JVS

Reputation: 2682

CollecitonView does not always display data correctly

I am trying to implement a UICollectionView with custom cells. The setup is the following:

The PFFiles of the images are saved within imageFileDic:[String:PFFile].

This is my UPDATED cellForItemAtIndexPath:

   let collectionCell:SettingsCollectionViewCell =
   collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell",
   forIndexPath: indexPath) as! SettingsCollectionViewCell


    if indexPath.row < imageFileDic.count {


        if let imageId = imageFileIds[indexPath.row] as? String {

            if let imageData = imageFileDic[imageId]{

                collectionCell.collectionViewImage.file = imageData
                collectionCell.collectionViewImage.loadInBackground()

            }

        }
    } else{

        collectionCell.collectionViewButton.setImage(UIImage(), forState: .Normal)
        collectionCell.collectionViewImage.image = UIImage(named: "CameraBild.png")

    }

Now sometimes (1/5 times) my application decides to display an image twice, or in the position of cell nr. 4.

in my query I am always deleting the dictionaries and arrays before appending new data.

Any ideas?

Edit: This is the PFQuery I am calling:

let imageQuery = PFQuery(className: "Images")
    imageQuery.whereKey("sender", equalTo: objectID!)
    imageQuery.addAscendingOrder("createdAt")
    imageQuery.cachePolicy = .NetworkElseCache

    imageQuery.findObjectsInBackgroundWithBlock { (objects, error) in
        if error != nil {
        createAlert(error!)
        }
        else{
            if let objects = objects{


                self.imageFileDic.removeAll()
                self.imageFileIds.removeAll()

                for object in objects{

                    if let id = object.objectId{
                        print("id found")
      if let imageFile = object.objectForKey("imageFile") as? PFFile{

                        self.imageFileIds.append(id)
                        self.imageFileDic[id] = imageFile



                            if object == objects.last{
                            print(self.imageFileIds.count)
                            print(self.imageFileDic.count)

                            self.mainCollectionView.reloadData()
                            }

                        }
                    }

                }
            }
        }
    }

}

Upvotes: 0

Views: 36

Answers (1)

Giang
Giang

Reputation: 2729

I think you should update image to main thread

dispatch_async(dispatch_get_main_queue()) { 
        collectionCell.collectionViewImage.file = imageData
        collectionCell.collectionViewImage.loadInBackground()
    }

Upvotes: 1

Related Questions