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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With