AlamofireImage how to clean memory and cache

2019-03-02 14:30发布

问题:

I use Alamofire and AlamofireImage in my app for get data and photos.

        Alamofire.request(.GET, URLString, encoding: .JSON)
        .authenticate(user: user, password: password)
        .responseJSON() { (response) -> Void in
          if let jsonResult = response.result.value {
            if jsonResult.count > 0 {
               ...
               let photo_url = jsonResult[index]["Photo_url"] as! String
               Alamofire.request(.GET, photo_url)
               .authenticate(user: user_photo, password: password_photo)
               .responseImage { response in
                  if let image = response.result.value
                  {
                     button.setBackgroundImage(image, forState: .Normal)
                  }
               }
            }
          }
        }

I have a crash if user use app for a long time. I can't caught it in the IOS simulator on mac, but I checked and I think if memory in phone finished user have a crash. I use Crashlytics for catch crash but I can't see this crash in the Crashlytics. I checked logs (access and error) in my Nginx server and also din't see any problems and errors.

After there I think it is problem with memory in the phone. How can I clean cache and memory if I use Alamofire? Can I clean cache Alamofire?

I tried to use this function and clean image in the cache before my photo_url request, but I have the same crash:

func clearImageFromCache(url: String) {
    let URL = NSURL(string: url)!
    let URLRequest = NSURLRequest(URL: URL)

    let imageDownloader = UIImageView.af_sharedImageDownloader

    // Clear the URLRequest from the in-memory cache
    imageDownloader.imageCache?.removeImageForRequest(URLRequest, withAdditionalIdentifier: nil)

    // Clear the URLRequest from the on-disk cache
    imageDownloader.sessionManager.session.configuration.URLCache?.removeCachedResponseForRequest(URLRequest)
}

回答1:

Updated for swift:

Used below simple function;

func clearImageFromCache(mYourImageURL: String) {
    let URL = NSURL(string: mYourImageURL)!
    let mURLRequest = NSURLRequest(url: URL as URL)
    let urlRequest = URLRequest(url: URL as URL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData)

    let imageDownloader = UIImageView.af_sharedImageDownloader
    _ = imageDownloader.imageCache?.removeImage(for: mURLRequest as URLRequest, withIdentifier: nil)
    self.mImageView.af_setImage(withURLRequest: urlRequest, placeholderImage: UIImage(named: "placeholder"), completion: { (response) in
        self.mImageView.image = response.result.value
    })
}

// NOTE:- where placeholder = your_placeholder_image_name