Search code examples
iosswiftcachingcachemanager

How to clear Cache in iOS?


TLDR: How, based on my current cacheManager, do I clear cache? What code should I use and how?

I have the bellow cacheManager class which I use to cache user created videos. 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)
        }
    }

}

I have now recently come across a problem which I asked about here.

To fix the problem i believe I need to clear cache. The problem is I dont know how to do this.

What I tried:

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

Used like this as soon as the first instance of fetching content occurs.

        CacheManager.clearCache()//Instance member 'clearCache' cannot be used on type 'CacheManager'; did you mean to use a value of this type instead?
        self.getFollowers()

Some info on how I use the cache manager:

  • For each media which is fetched I use the cache manager to store the video url (which I assume is the cached videoURL) for use when needed

Solution

  • To clear the cache directory contents you can call this method with it's 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)
    
        }
    
     }
    

    To call your method

    CacheManager.shared.clearCache()
    

    But note it's code is irelevant as it has a netwrok related code , and your content is stored in cache directory