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

时间:2016-08-09 17:17:56

标签: ios swift asynchronous imageurl

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

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

这是我的代码:

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

        }
    } 
}

1 个答案:

答案 0 :(得分:2)

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

<强> 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

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
}