1

我有一个显示图像的集合视图,其中一些被缓存并正确检索,而另一些则没有。集合视图每行显示两个方形单元格。

我不明白为什么有时图像是从缓存中获取的,而其他时候必须再次下载。

在这里我缓存图像:

class DataImage {

static let sharedManager = DataImage()

let decoder = ImageDecoder()
let photoCache = AutoPurgingImageCache(
    memoryCapacity: 100 * 1024 * 1024,
    preferredMemoryUsageAfterPurge: 60 * 1024 * 1024
)


//MARK: - Image Downloading

func getNetworkImage(urlString: String, completion: (UIImage -> Void)) -> (ImageRequest) {
    let queue = decoder.queue.underlyingQueue
    let request = Alamofire.request(.GET, urlString)
    let imageRequest = ImageRequest(request: request)
    imageRequest.request.response(
        queue: queue,
        responseSerializer: Request.imageResponseSerializer(),
        completionHandler: { response in
            guard let image = response.result.value else {
                return
            }
            let decodeOperation = self.decodeImage(image) { image in
                completion(image)
                self.cacheImage(image, urlString: urlString)
            }
            imageRequest.decodeOperation = decodeOperation
        }
    )
    return imageRequest
}

func decodeImage(image: UIImage, completion: (UIImage -> Void)) -> DecodeOperation {
    let decodeOperation = DecodeOperation(image: image, decoder: self.decoder, completion: completion)
    self.decoder.queue.addOperation(decodeOperation)
    return decodeOperation
}

//MARK: - Image Caching

func cacheImage(image: Image, urlString: String) {
    photoCache.addImage(image, withIdentifier: urlString)
}

func cachedImage(urlString: String) -> Image? {
    print("image: \(photoCache.imageWithIdentifier(urlString))")
    return photoCache.imageWithIdentifier(urlString)
}

}

这是 Cell 类:

class StoreCell: UICollectionViewCell {

@IBOutlet weak var title: UILabel!
@IBOutlet weak var storyImage: UIImageView!
@IBOutlet weak var subTitle: UILabel!
@IBOutlet weak var cost: UILabel!

var imageFilename: String!
var request: ImageRequest!
var dataImage = DataImage()


func configure() {
    self.layer.cornerRadius = 3.0
    reset()
    loadImage()
}

func reset() {
    storyImage.image = nil
    request?.cancel()
}

func loadImage() {

    let stringURL = "https://........\(imageFilename)"

    if self.storyImage.image == nil {
        if let image = dataImage.cachedImage(stringURL) {

            self.storyImage.image = image
        } else {
            request = dataImage.getNetworkImage(stringURL) { image in
                self.storyImage.image = image
                self.storyImage.runImageTransition(.CrossDissolve(0.2), withImage: image)
            }
        }
    }
}

}

4

1 回答 1

0

I will share all codes below.

FIRST You need to update ImageRequest class

import UIKit
import Alamofire

class ImageRequest {

    var decodeOperation: Operation?
    var request: DataRequest

    init(request: DataRequest) {
        self.request = request
    }

    func cancel() {
        decodeOperation?.cancel()
        request.cancel()
    }

}

SECOND

import UIKit
import Alamofire
import AlamofireImage

class DataImage {

    static let sharedManager = DataImage()
    let decoder = ImageDecoder()
    let photoCache = AutoPurgingImageCache(
        memoryCapacity: 100 * 1024 * 1024,
        preferredMemoryUsageAfterPurge: 60 * 1024 * 1024
    )

    //MARK: - Read Data

    func allPhotos() -> [GlacierScenic] {
        if !photos.isEmpty { return photos }
        guard let data = NSArray(contentsOfFile: dataPath()) as? [NSDictionary] else { return photos }
        for photoInfo in data {
            let name = photoInfo["name"] as! String
            let urlString = photoInfo["imageURL"] as! String
            let glacierScenic = GlacierScenic(name: name, photoURLString: urlString)
            photos.append(glacierScenic)
        }
        return photos
    }

    func dataPath() -> String {
        return Bundle.main.path(forResource: "GlacierScenics", ofType: "plist")!
    }

    //MARK: - Image Downloading

    func getNetworkImage(urlString: String, completion: @escaping ((UIImage) -> Void)) -> (ImageRequest) {
        let queue = decoder.queue.underlyingQueue
        let request = Alamofire.request(urlString)
        let imageRequest = ImageRequest(request: request)
        imageRequest.request.response(
    queue: queue,
            responseSerializer: DataRequest.imageResponseSerializer(),
            completionHandler: { response in
                guard let image = response.result.value else {
                    return
                }
                let decodeOperation = self.decodeImage(image) { image in
                    completion(image)
                    self.cacheImage(image, urlString: urlString)
                }
                imageRequest.decodeOperation = decodeOperation
            }
        )
        return imageRequest
    }

    func decodeImage(_ image: UIImage, completion: @escaping ((UIImage) -> Void)) -> DecodeOperation {
        let decodeOperation = DecodeOperation(image: image, decoder: self.decoder, completion: completion)
        self.decoder.queue.addOperation(decodeOperation)
        return decodeOperation
    }

    //MARK: - Image Caching

    func cacheImage(_ image: Image, urlString: String) {
        photoCache.add(image, withIdentifier: urlString)
    }

    func cachedImage(_ urlString: String) -> Image? {
        return photoCache.image(withIdentifier: urlString)
    }

}

THIRD

My pod file details.

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!

target 'projetname' do
  pod 'Alamofire', :git => 'https://github.com/Alamofire/Alamofire.git', :tag => '4.0.0'
  pod 'AlamofireImage', :git => 'https://github.com/Alamofire/AlamofireImage.git', :tag => '3.1.0'
end

post_install do |installer|
   installer.pods_project.targets.each do |target|
       target.build_configurations.each do |config|
           config.build_settings['SWIFT_VERSION'] = '3.0'
       end
   end
end
于 2016-10-05T01:02:39.047 回答