2016-12-22 2 views
1

Я вижу несколько подобных потоков на этом сайте, однако ни один не выясняет, как вернуть данные из массива.преобразование PFFile в UIImage с данными и добавление к массиву

Я пытаюсь к PFFile от сервера и установить его в качестве изображения в CollectionView

for object in packs { 

     self.packName.append(object["packName"] as! String) 
     self.packDescription.append(object["packDesctription"] as! String) 

     var objectImage = object["file"] as! PFFile 
     objectImage.getDataInBackground(block: { (imageData, error) in 

     if error == nil { 
      var myImage = UIImage(data: imageData!) 
      self.packImage.append(myImage!) 
     } 
     }) 

    } 

печать packImage представляет собой кучу данных: так что есть что-то в нем ..

[<UIImage: 0x608000287210>, {259, 194}] 
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}] 
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}, <UIImage: 0x6080002870d0>, {249, 192}] 
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}, <UIImage: 0x6080002870d0>, {249, 192}, <UIImage: 0x6080002873f0>, {222, 160}] 
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}, <UIImage: 0x6080002870d0>, {249, 192}, <UIImage: 0x6080002873f0>, {222, 160}, <UIImage: 0x600000286ea0>, {255, 198}] 
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}, <UIImage: 0x6080002870d0>, {249, 192}, <UIImage: 0x6080002873f0>, {222, 160}, <UIImage: 0x600000286ea0>, {255, 198}, <UIImage: 0x608000287670>, {261, 193}] 
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}, <UIImage: 0x6080002870d0>, {249, 192}, <UIImage: 0x6080002873f0>, {222, 160}, <UIImage: 0x600000286ea0>, {255, 198}, <UIImage: 0x608000287670>, {261, 193}, <UIImage: 0x600000286cc0>, {259, 194}] 
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}, <UIImage: 0x6080002870d0>, {249, 192}, <UIImage: 0x6080002873f0>, {222, 160}, <UIImage: 0x600000286ea0>, {255, 198}, <UIImage: 0x608000287670>, {261, 193}, <UIImage: 0x600000286cc0>, {259, 194}, <UIImage: 0x608000287800>, {189, 267}] 
[<UIImage: 0x608000287210>, {259, 194}, <UIImage: 0x600000287350>, {259, 194}, <UIImage: 0x6080002870d0>, {249, 192}, <UIImage: 0x6080002873f0>, {222, 160}, <UIImage: 0x600000286ea0>, {255, 198}, <UIImage: 0x608000287670>, {261, 193}, <UIImage: 0x600000286cc0>, {259, 194}, <UIImage: 0x608000287800>, {189, 267}, <UIImage: 0x600000287620>, {259, 194}] 

Однако, когда я пытаюсь установить изображение ниже, я получаю индекс ошибки вне диапазона.

cell.imageCell.image = packImage[indexPath.row] 

---------- РЕДАКТИРОВАТЬ ATTACHED Полный код UICollectionViewDelegate ----------------

import UIKit 
import Parse 

private let reuseIdentifier = "Cell" 

class PackViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { 

    //have to drag in outlet because not in CVC anymore 
    @IBOutlet var collectionView: UICollectionView! 

    //var delegate: PackViewDelegate? 

    var packName = [""] // the total packs in the app 
    var packDescription = [""] 
    var packTitle = [""] 
    var packImage = [UIImage]() 

    override func viewDidLoad() { 
     super.viewDidLoad() 


     let packQuery = PFQuery(className: "Pack") 

     packQuery.findObjectsInBackground(block: { (objectsArray, error) in 
      if error != nil { 
       print(error!) 
      } else if let packs = objectsArray { 

       self.packName.removeAll() // remove the empty strings 
       //self.packImage.removeAll() 
       self.packDescription.removeAll() 

       for object in packs { 

        self.packName.append(object["packName"] as! String) 
        self.packDescription.append(object["packDesctription"] as! String) 

        // get the PFFile from the server 
        var objectImage = object["file"] as! PFFile 
        objectImage.getDataInBackground(block: { (imageData, error) in 

         if error == nil { 
          //convert the data to an image and append it to array 
          var myImage = UIImage(data: imageData!) 
          self.packImage.append(myImage!) 
          print(self.packImage) 
         } 
        }) 

       } 

       //only works when create iboutlet of collection view because in VC not CVC 
       self.collectionView?.reloadData() 

      } 
     }) 

    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 

    } 


    // MARK: UICollectionViewDataSource 

    func numberOfSections(in collectionView: UICollectionView) -> Int { 
     return 1 
    } 


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


    func UIColorFromHEX(hexValue: UInt) -> UIColor { 
     return UIColor(
      red: CGFloat((hexValue & 0xFF0000) >> 16)/255.0, 
      green: CGFloat((hexValue & 0x00FF00) >> 8)/255.0, 
      blue: CGFloat(hexValue & 0x0000FF)/255.0, 
      alpha: CGFloat(1.0) 
     ) 
    } 


    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     let cell: PackCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PackCollectionViewCell 


     cell.labelCell.text = packDescription[indexPath.row] 

//////-------------------------------------------------------------- this is where it crashes 
     cell.imageCell.image = packImage[indexPath.row] 



     cell.imageCell.layer.masksToBounds = true 
     cell.imageCell.layer.cornerRadius = cell.imageCell.frame.height/2 

     cell.imageCell.layer.borderWidth = 3 
     cell.imageCell.layer.borderColor = UIColorFromHEX(hexValue: 0x62aca2).cgColor 

     return cell 

    } 


    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 

      // handle the segue to JourneyViewController with variable "selectedPack" 
      // not sure why you need to set the storyboard but it works 
     let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) 
      //create instance of the viewcontroller 
     let transportJourneyViewController = storyBoard.instantiateViewController(withIdentifier: "JourneyViewController") as! JourneyViewController 
      //value to pass - has been defined in journey 
     transportJourneyViewController.selectedPack = packName[indexPath.row] 
      //present the vc 
     self.present(transportJourneyViewController, animated:true, completion:nil) 

    } 


    @IBAction func logoutButtonTapped(_ sender: Any) { 
     PFUser.logOut() 
     if (PFUser.current() == nil) { 
      performSegue(withIdentifier: "segueLogout", sender: self) 
     } else { 
      MyFunctions.createAlert(errorTitle: "Oops...", errorMessage: "Something happened when logging you out.", className: self) 
     } 
    } 

} // class 

enter image description here

+0

Добавить код метода делегата TableView numberOfRowsInSection в ваш вопрос? –

+0

его странный, есть 9 ячеек, но этот массив выходит за пределы диапазона с 9 элементами? Я уверен, что это как-то связано с преобразованием файла из данных в UIImage, но не может его увидеть. – Pippo

+0

вы попробовали мой ответ? –

ответ

2

Я думаю, что есть проблема в вашем array. Ваш

packName.count > self.packImage.count 

Используйте этот массив self.packImage в numberOfItemsInSectionto методе удаления проникнуть 'зайцу'

Попробуйте

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

Надеется, что это поможет вам

+0

Да удаляет сбой. Все еще не удается показать изображение с помощью cell.imageCell.image = packImage [indexPath.row] – Pippo

+0

просто прокомментируйте эту строку cell.imageCell.layer.cornerRadius = cell.imageCell.frame.height/2 если оно отображает изображение, тогда мы обсудит на нем –

+0

, так как сменил на self.packImage.count ни один другой дисплей данных, такой как packDescription или border ect. при комментировании углового радиуса 2 элемента отображаются со всей границей, описанием ect, но должно быть 9? – Pippo

0
indexPath.row 

Индекса номер, идентифицирующий строку в раздел просмотра таблицы.

indexPath.item 

Номер индекса, идентифицирующий элемент в разделе вида коллекции.

Используйте cell.imageCell.image = packImage[indexPath.item] вместо cell.imageCell.image = packImage[indexPath.row], так как его вид сбоку. И проверьте свой номерOfItemsInSection в источнике данных коллекции, который меньше или равен вашему массиву packDescription, packImage.

+0

спасибо за указание .item out. к сожалению, проблема, похоже, связана с конверсией из PFFile в UIImage – Pippo

Смежные вопросы