IOS - SWIFT - CollectionView & # 8594; ImageView download url
I have a CollectionView with images that need to be loaded from the web.
The urls are in an array of strings, and in the collectionView cell is the imageView.
and I found this code:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! ViewCell
var url = NSURL(string: "\(array[indexPath.row])")
var err: NSError?
var imageData: NSData = NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)!
var bgImage = UIImage(data:imageData)
cell.imgView.image = bgImage
// cell.imgView.image = UIImage(named: array[indexPath.row])
cell.load.hidden = false
cell.load.startAnimating()
cell.load.hidesWhenStopped = true
if cell.imgView.image == nil {
cell.load.startAnimating()
}else{
cell.load.stopAnimating()
}
return cell
}
the problem only occurs at the beginning. the app is loaded and I can see some commands from println in my MainVC (which is with collectionView), but on the ipad it just fires up the startup screen.
I tried to point the entry point to another view and it works fine until I go to MainVC, everything just flips over and goes to any clicks.
what could be wrong with that?
Thanks for any help!
source to share
This is because you are uploading the image to the main thread below the line of code.
var imageData: NSData = NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)!
Load the image asynchronously and update the corresponding cell after the image is loaded.
http://jamesonquave.com/blog/developing-ios-apps-using-swift-part-5-async-image-loading-and-caching/
source to share