AlamofireImage如何清理内存和缓存

时间:2016-10-10 11:36:18

标签: swift memory alamofire alamofireimage

我在我的应用中使用Alamofire和AlamofireImage来获取数据和照片。

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

如果用户长时间使用应用程序,我会崩溃。我无法在Mac上的IOS模拟器中捕获它,但我检查了一下,我认为如果手机中的内存用户崩溃了。我使用Crashlytics进行捕获崩溃但我无法在Crashlytics中看到这种崩溃。 我检查了我的Nginx服务器中的日志(访问和错误),也没有看到任何问题和错误。

在那之后,我认为手机内存有问题。如果我使用Alamofire,我该如何清理缓存和内存?我可以清理缓存Alamofire吗?

我尝试使用此功能并在我的photo_url请求之前清理缓存中的图像,但我遇到了同样的崩溃:

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 个答案:

答案 0 :(得分:0)

  

更新了swift:

在简单函数下使用;

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

//注意: - 其中placeholder = your_placeholder_image_name

相关问题