本文介绍了Swift:无法从Internet下载图像并缓存它们。需要建议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,我正在构建一个应用程序,该应用程序可以从Internet下载图像并在UICollectionView中显示,我可以成功实现此功能,但是,看起来好像超时滚动屏幕,它又重新下载了图像再次,这可能会导致用户的大量数据。我发现我可以使用缓存来解决此问题,但是它没有用,我认为我做的一切都正确,但是似乎数据没有存储在缓存中。这是代码,有人可以帮助我解决这个问题吗?谢谢

I am new to swift, and I am building an App that download images from the Internet and display in a UICollectionView, I can achieve this function successfully, however, it seems like overtime you scroll the screen, it downloaded the images again and again, which may causes a lot of data of the users. I found that I can use cache to solve this problem, but it didn't work, I think I did everything right, but seems the data didn't stored in the cache. here is the code, anyone can help me solve this? thanks

var imageCache = [String: UIImage]()
class ViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

extension ViewController: UICollectionViewDataSource {

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 5
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell

    Alamofire.request(.GET, "http://localhost:8888/wordpress/wp-json/wp/v2/posts").responseJSON { (response) in
        if let jsonFile = response.result.value {

            var arrayOfPosts = [Posts]()

            for post in jsonFile as! NSArray {

                let postObj = Posts()
                postObj.postThumbnailUrlString = post.valueForKeyPath("featured_image_thumbnail_url") as! String

                arrayOfPosts.append(postObj)
            }


            let imageUrlString: String = arrayOfPosts[indexPath.row].postThumbnailUrlString

            let imageUrl: NSURL = NSURL(string: imageUrlString)!







            if let imageFromCache = imageCache[imageUrlString] {

                cell.imageView.image = imageFromCache
                return
            }

            let request = NSURLRequest(URL: imageUrl)
            let session = NSURLSession.sharedSession()
            let dataTask = session.dataTaskWithRequest(request) { (data, response, error) in

                let imageToCache = UIImage(data: data!)

                imageCache[imageUrlString] = imageToCache

                dispatch_async(dispatch_get_main_queue(), {



                    cell.imageView.image = imageToCache
                })

            }

            dataTask.resume()



        }

    }


   return cell

}}

我也有一类帖子和定制的c ollectionviewcell。这给我存了很长时间,真的希望有人能帮助我解决这个问题。谢谢!!

I also have a class of Posts and a customized collectionviewcell. this stocked me a long time, really hope anyone can help me solve this problem. thanks!!

推荐答案

使用

Swift 2.2或2.3

添加-> pod文件中的pod'AlamofireImage','〜> 2.5'。

Add --> pod 'AlamofireImage', '~> 2.5' in your pod file.

Swift 3.1

添加-> pod'AlamofireImage','〜> 3.3'在您的pod文件中。

Add --> pod 'AlamofireImage', '~> 3.3' in your pod file.

将以下行放入代码中自动缓存图像并下载它。

Put the following line in your code which will automatically cache the image and download it as well.

override func viewDidLoad() {
     super.viewDidLoad()
     //hit your web service here to get all url's
 }

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
   return arrImageURL.count
}


func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
   cell.imgViewPhoto.af_setImageWithURL(arrImageURL[indexPath.row], placeholderImage: UIImage())
}

这篇关于Swift:无法从Internet下载图像并缓存它们。需要建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 23:26