0

I was trying to make a wallpaper app and my code was working all fine when I had the entire implementation in the ViewController file. And then I shifted some of the code to another class. Here is the code.

ViewController.swift

override func viewDidLoad() {
    super.viewDidLoad()

    photoOperations.getStuffFromJson()
 }



func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return photoOperations.previewUrlArray.count

}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

  let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollectionViewCell

    cell.backgroundColor = UIColor.whiteColor()

    if let img = self.images[indexPath] {

                cell.imageView.image = img

            } else {

               photoOperations.downloadThumbnail(indexPath.row){ (image) in

                    dispatch_async(dispatch_get_main_queue()) {
                        if let img = image {

                            cell.imageView.image = img
                            self.images[indexPath] = img

                        } else {


                            print("Images will be loaded in a few seconds!")

                      }
                     }
                    }
                   }

   return cell
}

PhotoOperations.swift

func getStuffFromJson(  ){

    Alamofire.request(.GET, "https://example.com/api/", parameters: ["key": "123.."])
        .responseJSON{ response in
            if let value = response.result.value  {

                let hits = JSON(value)["hits"]
                var counter = 0

                while counter < hits.count {

                    if let previewString = hits[counter]["previewURL"].rawString(){

                        self.previewURL = NSURL(string: previewString)!
                        self.previewUrlArray.append(self.previewURL!)
                        counter += 1


                    } else{   print("Error : A previewURL wasn't found.")
  }}}}}



func downloadThumbnail(forIndexPathAtRow : Int , completion: (UIImage?)->Void) {

    if previewUrlArray.count > 0 {

        ...  // create URL task , session etc. 
    }

}

How do I reload the data in the ViewController? I tried adding a collectionView parameter to the getStuffFromJSON method and calling collectionView.reload at the end. But that doesn't work. Also I get 0 as previewURLArray.count in the numberOfItemsInSection method.

209135
  • 517
  • 5
  • 15
  • You should add a completion closure on your `getStuffFromJson ` and pass the array back to the viewcontroller, then inside there do reload, i see the `downloadThumbnail ` you are already doing it, but why not do for the other one? – Tj3n Sep 09 '16 at 02:56
  • It didn't even occur to me. Thank's a lot – 209135 Sep 09 '16 at 06:07
  • What wasnt not occurred? Dont pass the tableView to the function but write completion closure and let the vc pass code to it – Tj3n Sep 09 '16 at 07:11

1 Answers1

0

Did you try to set images out of the dispatch_async and reloadData() method into the dispatch_async ?

I have developed basic similar app which works with Alamofire Pod .

In download / fetch function used the settings works than later in a dispatch block called the reloadData() of my tableView

There is a one difference , i worked with tableView , your app works with collectionView

dispatch_async(dispatch_get_main_queue(), {
            self.tableView.reloadData();
 })

A small part of my app

//user reference

let user : User = User()

//dictionary , contains json datas

user.setValuesForKeysWithDictionary(dictionary);

tableView works with users , String array . Before the dispatch_async append user to it then call reloadData() in the async

Then

self.users.append(user);
dispatch_async(dispatch_get_main_queue(), {
        self.tableView.reloadData();
})
eemrah
  • 1,603
  • 3
  • 19
  • 37