2016-10-03 51 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只是內存,當您重新啓動應用程序時,應用程序的內存將被回收。