How to correctly store the data that retrieved from sever?

时间:2018-03-25 18:53:57

标签: ios swift uitableview uicollectionview

I defined var postImgData = [UIImage]() at beginning of class to store all the images get from sever. The following is the code to get the image from sever

func loadPosts(){
    let query = PFQuery(className: "posts")
    query.whereKey("username", equalTo:PFUser.current()!.username!) 
    query.skip = self.picArray.count // skip the already loaded images

    query.findObjectsInBackground { (objects, error) in

        if error == nil {

         if let objects  = objects{ 
            for object in objects{       
                self.collectionView?.performBatchUpdates({
                    let indexPath = IndexPath(row: self.uuidArray.count, section: 0)
                    self.uuidArray.append(object.value(forKey: "uuid") as! String)
                    self.picArray.append(object.value(forKey: "pic") as! PFFile)
                    self.collectionView?.insertItems(at: [indexPath])
                }, completion: nil)

            }
          }
        } else{
            print(error!.localizedDescription)
        }
    }
 }

Then i want to use self.postImgData[indexPath.row] = UIImage(data: data!)! to save each image data into postImgData array that defined earlier. But when i run the app it gives error said this line self.postImgData[indexPath.row] = UIImage(data: data!)! Thread 1: Fatal error: Index out of range. I am not sure why its happening? I tried use append function and its working but its didn't show the correct photo when i selected each cell. I am note sure what is correct way to do that? thanks

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

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    //define cell

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! pictureCell

    picArray[indexPath.row].getDataInBackground { (data, error) in

        if error == nil {
            cell.picImg.image = UIImage(data: data!)

           self.postImgData[indexPath.row] = UIImage(data: data!)!

        } else {
            print(error!.localizedDescription)
        }
    }
    return cell
}

0 个答案:

没有答案
相关问题