如何清除 iOS 中的缓存?

How to clear Cache in iOS?

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

我有下面的 cacheManager class,我用它来缓存用户创建的视频。

 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

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("\([=10=])"))")! }

        urls.forEach {  try? FileManager.default.removeItem(at: [=10=]) } 

        let con = try FileManager.default.contentsOfDirectory(atPath: url.path)

        print("after \(con)")

    } 
    catch {

        print(error)

    }

 }

调用你的方法

CacheManager.shared.clearCache()

但请注意,它的代码是不相关的,因为它有一个与网络相关的代码,并且您的内容存储在缓存目录中