swift - AlamofireImage如何清理内存和缓存

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

最佳答案

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

//注意:- 其中占位符 = your_placeholder_image_name

关于swift - AlamofireImage如何清理内存和缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39957363/

相关文章:

swift - Swift 中的闭包和回调有什么区别?

java内存不足然后退出

java - 哪里可以找到如何计算 java 对象大小的证据

ios - 打印 url 时的 Xcode EXC_BREAKPOINT (code=1, subcode=...)

ios - AlamofireImage 下载到 CoreData

ios - 使用 Alamofire 路由器显示事件指示器

ios - AWSS3 区域/plist 配置问题 'The service configuration is ` nil`

objective-c - 将 Objective-C 转换为 Swift 以模拟 S3

ios - CLGeocoder CompletionHandler

ios - 快速将数据从 tableview 传递到 viewController