如何从URL加载图像到imageView,而不是集体?

时间:2022-01-21 00:30:05

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.

我正在尝试将一些图像从URL加载到我的imageView,但是我的代码设置方式,应用程序等待下载整个图像集,然后才向用户显示图像。一旦打开应用程序,这会导致大量的等待时间。

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?

要删除等待时间,只要从webURL一个一个地下载图像,就必须将图像加载到imageView。有人可以建议怎么做吗?

Here is my code:

这是我的代码:

ViewController.swift

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

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!)

        }
    } 
}

1 个解决方案

#1


2  

You have to download the image when the cell is being displayed.

您必须在显示单元格时下载图像。

ImageFetcher.swift

ImageFetcher.swift

class ImageFetcher {
    var images:[NSIndexPath: UIImage] = [:]
    func downloadImage(completion: (UIImage?)->Void) {
        let session = NSURLSession.sharedSession()
        if let url = self.imageURL {
            let imageURL = NSURL(string: url)

            let request = NSURLRequest(URL: imageURL!)

            let task = session.dataTaskWithRequest(request) {data, response, downloadError in

                if let imageData = data, image = UIImage(data: imageData) {
                    completion(image)
                } else {
                    completion(nil)
                }
            } 
            task.resume()
        } else {
            completion(nil)
        }

    }
}

ViewController.swift

ViewController.swift

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

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

   cell.imageView.image = nil //or the placeholder image

   if let img = imageFetcher.images.valueForKey[indexPath] {
      cell.imageView.image = img
   } else {
      imageFetcher.downloadImage({ (image) in

            dispatch_async(dispatch_get_main_queue(), {
                if let img = image {
                    let c = collectionView.cellForItemAtIndexPath(indexPath) as! CollectionViewCell
                    c.imageView.image = img
                    imageFetcher.images[indexPath] = img
                } else {
                    print("Error!")
                }
            })

        })
   }


   return cell
}

#1


2  

You have to download the image when the cell is being displayed.

您必须在显示单元格时下载图像。

ImageFetcher.swift

ImageFetcher.swift

class ImageFetcher {
    var images:[NSIndexPath: UIImage] = [:]
    func downloadImage(completion: (UIImage?)->Void) {
        let session = NSURLSession.sharedSession()
        if let url = self.imageURL {
            let imageURL = NSURL(string: url)

            let request = NSURLRequest(URL: imageURL!)

            let task = session.dataTaskWithRequest(request) {data, response, downloadError in

                if let imageData = data, image = UIImage(data: imageData) {
                    completion(image)
                } else {
                    completion(nil)
                }
            } 
            task.resume()
        } else {
            completion(nil)
        }

    }
}

ViewController.swift

ViewController.swift

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

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

   cell.imageView.image = nil //or the placeholder image

   if let img = imageFetcher.images.valueForKey[indexPath] {
      cell.imageView.image = img
   } else {
      imageFetcher.downloadImage({ (image) in

            dispatch_async(dispatch_get_main_queue(), {
                if let img = image {
                    let c = collectionView.cellForItemAtIndexPath(indexPath) as! CollectionViewCell
                    c.imageView.image = img
                    imageFetcher.images[indexPath] = img
                } else {
                    print("Error!")
                }
            })

        })
   }


   return cell
}