Swift:从Internet下载图像并缓存它们无法正常工作。需要建议

时间:2016-08-11 06:47:21

标签: swift caching uicollectionview alamofire

我是swift的新手,我正在构建一个从互联网上下载图像并在UICollectionView中显示的应用程序,我可以成功实现这个功能,但是,看起来像加班你滚动屏幕,它再次下载图像而且,这可能会导致很多用户的数据。我发现我可以使用缓存来解决这个问题,但它没有用,我想我做的一切都正常,但似乎数据没有存储在缓存中。这是代码,有谁可以帮我解决这个问题?谢谢

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

}}

我还有一类帖子和一个自定义的collectionviewcell。这让我感觉很长时间,真的希望有人能帮我解决这个问题。谢谢!

2 个答案:

答案 0 :(得分:2)

使用AlamofireImage

Swift 2.2或2.3

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

Swift 3.1

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

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

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())
}

答案 1 :(得分:0)

Kingfisher是一个轻量级的纯Swift实现库,用于从Web下载和缓存图像。该项目受到流行的SDWebImage的启发。它为您提供了在下一个应用程序中使用纯Swift替代品的机会。 kingfisher