I am trying to load a couple images from a URL to my imageView
but the way my code is set up, the app waits for the entire set of images to be downloaded and only then are the images displayed to the user. This causes a massive amount of waiting time once the application is opened.
To remove the waiting time, the images must be loaded to the imageView
as soon as they are downloaded from the webURL, one by one.
Could someone suggest how to do this?
Here is my code:
ViewController.swift
class ViewController: UIViewController , UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
let imageFetcher = ImageFetcher()
var counter = 0
override func viewDidLoad() {
super.viewDidLoad()
imageFetcher.setImageURL()
NSTimer.scheduledTimerWithTimeInterval(01, target: self, selector: #selector(addCells), userInfo: nil, repeats: true)
// Do any additional setup after loading the view, typically from a nib.
}
func addCells(timer : NSTimer){
if(counter == imageFetcher.ImageArray.count){
timer.invalidate()
return
}
counter = counter + 1
let indexPath = NSIndexPath(forItem: counter-1 , inSection: 0)
collectionView.insertItemsAtIndexPaths([indexPath])
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("numberOfItemsInSection method just ran") //timeline indicator
return counter
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCell", forIndexPath: indexPath) as! CollectionViewCell
cell.imageView.image = imageFetcher.ImageArray[indexPath.row]
return cell
}
}
ImageFetcher.swift
class ImageFetcher {
var newImage : UIImage?
var ImageArray = [UIImage]()
var imageURL : NSURL?{
didSet{ newImage = nil
Adder()
}
}
func setImageURL(){
imageURL = DemoURLs.randomImageUrl
}
func fetchImage() {
if let url = imageURL{
let imageData = NSData(contentsOfURL: url)
if imageData != nil{
self.newImage = UIImage( data: imageData! )
} else {
self.newImage = nil
}
}
}
func Adder(){
for _ in 1...20 {
fetchImage()
ImageArray.append(newImage!)
}
}
}