Swift: How remove Cashed Responses from URLCache by date

478 Views Asked by At

What I'm try to do?

Remove existing responses in URLCache prior a given date.

How I try to do that?

removeCachedResponses(since: date)

 func resetCache(_ since: Date) {
        self.cache.removeCachedResponses(since: since)
    }

Cashed responses where stored with:

...
let cachedData = CachedURLResponse(response: response, data: data)
self.cache.storeCachedResponse(cachedData, for: request)
...

Deleting cached responses works with

self.cache.removeAllCachedResponses()

EDIT: Only when you wait a bit. Imho the removing is done async. For that reason not every image is deleted immediately from cache. So I decided to add a small wait before start loading fresh one.

func reloadImages() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            self.loadImages(for: self.dataModel.loadDemoData(count: 5))
        }
        
    }

and

self.cache.removeCachedResponse(for: request)

But the cashed request aren't removed Do I have to use specify a specific date format or do I have to save a date value during storing the cache?

0

There are 0 best solutions below