如何清除iOS中的缓存?

时间:2019-05-11 18:42:20

标签: 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()

有关如何使用缓存管理器的一些信息:

  • 对于每种提取的媒体,我使用缓存管理器存储视频网址(我认为是缓存的videoURL),以便在需要时使用

1 个答案:

答案 0 :(得分:1)

要清除缓存目录的内容,可以使用其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相关的代码,并且您的内容存储在缓存目录中