Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download image from URL in loop for collection view

Im trying to create a collection view of images. I've tried these solutions, to download the images:
one
two
three
And
four

var tempObject = json["photos"]
                for var i = 0; i < tempObject.count; i++
                {
                    var tempImage = UIImage()

                    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {

                        tempImage =  UIImage(data: NSData(contentsOfURL: NSURL(string:"https://developer.apple.com/swift/images/swift-og.png")!)!)!
                    })

                    swiftImages.insert(tempImage, atIndex: i)
                }

                dispatch_async(dispatch_get_main_queue()) {

                    self.collectionView?.reloadData()
                }

But i can't get it to display the images. I'm new to networking with swift.

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! ImageCollectionViewCell
        cell.imageView.image = swiftImages[indexPath.row]
        return cell
    }
like image 210
Egghead Avatar asked Oct 31 '22 10:10

Egghead


1 Answers

you are adding UIImage() (the one created just before dispatch_async block) objects to swiftImages array. Please realize that dispatch_async block is executed sometime in future, It is not executed right after var tempImage = UIImage() line. Grab the image from inside dispatch block, also that's where you should fire the dispatch to main queue to reload collection. Change your code like this:

            var tempObject = json["photos"]
            for var i = 0; i < tempObject.count; i++
            {
                dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {

                    var tempImage =  UIImage(data: NSData(contentsOfURL: NSURL(string:"https://developer.apple.com/swift/images/swift-og.png")!)!)!
                    swiftImages.insert(tempImage, atIndex: i)
                    dispatch_async(dispatch_get_main_queue()) {

                       self.collectionView?.reloadData()
                    }
                })
            }

btw loading images for collection view or table view cells is not just about reading the images, you might some time by using something like AlamofireImage.

like image 187
ishaq Avatar answered Nov 14 '22 05:11

ishaq