ios - 如何清除iOS中的缓存?

标签 ios swift caching cachemanager

TLDR :如何基于当前的cacheManager清除缓存?我应该使用什么代码以及如何使用?

我有下面的cacheManager类,用于缓存用户创建的视频。 More info on how I use it is here

 public enum Result<T> {
    case success(T)
    case failure(NSError)
}

class CacheManager {

    static let shared = CacheManager()
    private let fileManager = FileManager.default
    private lazy var mainDirectoryUrl: URL = {

        let documentsUrl = self.fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first!
        return documentsUrl
    }()

    func getFileWith(stringUrl: String, completionHandler: @escaping (Result<URL>) -> Void ) {

        let file = directoryFor(stringUrl: stringUrl)

        //return file path if already exists in cache directory
        guard !fileManager.fileExists(atPath: file.path)  else {
            completionHandler(Result.success(file))
            return
        }

        DispatchQueue.global().async {

            if let videoData = NSData(contentsOf: URL(string: stringUrl)!) {
                videoData.write(to: file, atomically: true)
                DispatchQueue.main.async {
                    completionHandler(Result.success(file))
                }
            } else {
                DispatchQueue.main.async {
                    let error = NSError(domain: "SomeErrorDomain", code: -2001 /* some error code */, userInfo: ["description": "Can't download video"])

                    completionHandler(Result.failure(error))
                }
            }
        }
    }

    private func directoryFor(stringUrl: String) -> URL {

        let fileURL = URL(string: stringUrl)!.lastPathComponent
        let file = self.mainDirectoryUrl.appendingPathComponent(fileURL)
        return file
    }

    public func clearCache() {
        //Delete Cookies
        if let cookies = HTTPCookieStorage.shared.cookies {
            for cookie in cookies {
                NSLog("\(cookie)")
            }
        }

        let storage = HTTPCookieStorage.shared
        for cookie in storage.cookies! {
            storage.deleteCookie(cookie)
        }
    }

}

我最近遇到了一个问题which I asked about here

为了解决这个问题,我相信我需要清除缓存。问题是我不知道该怎么做。

我试过的
    public func clearCache() {
    //Delete Cookies
    if let cookies = HTTPCookieStorage.shared.cookies {
        for cookie in cookies {
            NSLog("\(cookie)")
        }
    }

    let storage = HTTPCookieStorage.shared
    for cookie in storage.cookies! {
        storage.deleteCookie(cookie)
    }
}

第一个获取内容的实例出现时,便像这样使用。
        CacheManager.clearCache()//Instance member 'clearCache' cannot be used on type 'CacheManager'; did you mean to use a value of this type instead?
        self.getFollowers()

有关如何使用缓存管理器的一些信息:
  • 对于获取的每种媒体,我使用缓存管理器存储视频URL(我认为是缓存的videoURL),以便在需要时使用
  • 最佳答案

    要清除缓存目录的内容,可以使用其URL调用此方法

    func clearContents(_ url:URL) { 
    
        do {
    
            let contents = try FileManager.default.contentsOfDirectory(atPath: url.path)
    
            print("before  \(contents)")
    
            let urls = contents.map { URL(string:"\(url.appendingPathComponent("\($0)"))")! }
    
            urls.forEach {  try? FileManager.default.removeItem(at: $0) } 
    
            let con = try FileManager.default.contentsOfDirectory(atPath: url.path)
    
            print("after \(con)")
    
        } 
        catch {
    
            print(error)
    
        }
    
     }
    

    调用方法
    CacheManager.shared.clearCache()
    

    但是请注意,它的代码无关紧要,因为它具有与netwrok相关的代码,并且您的内容存储在缓存目录中

    关于ios - 如何清除iOS中的缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56093276/

    相关文章:

    ios - 推送通知 - 当应用程序从后台关闭时设置 rootViewController

    ios - 在整个应用程序中禁用 UITextField 的自动更正

    objective-c - Objective-C : Passing method parameter to a block inside a block?

    swift - NSCompoundPredicate 和 Cloudkit

    ios - 如何为每个语句添加一个对象数组

    hibernate - 如何使域实例关联无效/刷新?

    caching - 大数据集的 Apollo InMemoryCache 性能策略(React)

    ios - Swift - [NSObject : AnyObject] !' is not a subtype of ' Dictionary<String, AnyObject>

    ios - 避免嵌套 Rx 订阅调用 - 原因是什么?

    bash - 我可以从 CLI 缓存 Linux 上命令的输出吗?