2016-10-03 52 views
0

我正在使用(尝试)AlamofireImage。 我的保存到缓存图像并未真正保存。AlamofireImage保存到缓存图像并非真正保存

我的代码包括:

import Alamofire 
import AlamofireImage 

let imageCache = AutoPurgingImageCache(
    memoryCapacity: 100 * 1024 * 1024, 
    preferredMemoryUsageAfterPurge: 60 * 1024 * 1024 
) 

然后我使用保存图像自己:

imageCache.add(image, withIdentifier: path) 

但在接下来的运行,它总是返回零当我尝试使用,以获取该图像相同的路径:

if let image = imageCache.image(withIdentifier: path){ 
    return image 
} 
return nil 

我做错了什么?

  • 而运行\调试我可以看到imageCache-currentMemoryUsage = 0

感谢。

回答

0

你不需要调用add()方法。我创建了包装Alamofire图像缓存的自定义类。

class ImageManager: NSObject { 
    static let shared = ImageManager() 
    private var imageDownloader: ImageDownloader! 
    private var imageCache: AutoPurgingImageCache! 


    // Configuration 
    var maximumActiveDownloads = 5 
    var placeholderImage: UIImage! 
    var imageTransitionDuration: NSTimeInterval = 0.5 

    // The total memory capacity of the cache in MB. 
    var memoryCapacity: UInt64 = 150 

    //The preferred memory usage after purge in MB. During a purge, images will be purged until the memory capacity drops below this limit. 
    var memoryUsageAfterPurge: UInt64 = 60 


    private override init() { 
     super.init() 

     imageCache = AutoPurgingImageCache(
      memoryCapacity: memoryCapacity * 1024 * 1024, 
      preferredMemoryUsageAfterPurge: memoryUsageAfterPurge * 1024 * 1024 
     ) 

     imageDownloader = ImageDownloader(
      configuration: ImageDownloader.defaultURLSessionConfiguration(), 
      downloadPrioritization: .FIFO, 
      maximumActiveDownloads: maximumActiveDownloads, 
      imageCache: imageCache 
     ) 

     UIImageView.af_sharedImageDownloader = imageDownloader 
    } 


    func setImageOrPlaceholder(onImageView imageView: UIImageView, stringURL: String?) { 
     guard let correctURL = NSURL.getURL(fromString: stringURL) else { 
      //debug("URL incorrect!: \(stringURL)", isError: true) 

      imageView.image = placeholderImage 
      return 
     } 

     let imageTransition: UIImageView.ImageTransition = .CrossDissolve(imageTransitionDuration) 

     imageView.af_setImageWithURL(correctURL, 
            placeholderImage: placeholderImage, 
            filter: nil, 
            imageTransition: imageTransition, 
            completion: { response in 
             //   debug("\(response.result.value)") 
     }) 
    } } 
0

但在接下来的运行,它总是返回零,当我尝试使用相同的路径来获取这一形象:

这听起来像你重新启动应用程序。 ImageCache只是内存,当您重新启动应用程序时,应用程序的内存将被回收。