Search code examples
iosswiftcachingalamofire

IOS how to prevent downloaded images from caching programmatically


I'm developing social networking App, it downloads user's profile photo from server every time profile view is opened. I haven't implemented any caching yet. But it seems that iOS doing that automatically.

The problem is that some time when user updates profile photo even though I can see that image has been successfully uploaded to server, it can take a while until on other devices users can see updated photo. I noticed that if after updating profile photo I reinstall app it will get latest image instantly. So my only assumption is that even though my app sends request to download image from server every time when profile view is opened, that request not always get executed by iOS, instead iOS provides cached copy.

If I'm right please can someone tall me how I can fix this issue. Do I need to perform cache deletion manually?

I'm using Alamofire and Xcode 6.4

UPDATE: It seems to me that adding two following lines to the AppDelegate solved the issue.

    let sharedCache:NSURLCache  = NSURLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
    NSURLCache.setSharedURLCache(sharedCache)

Solution

  • Alamofire uses NSURLCache in the background so you just have to call:

    NSURLCache.sharedURLCache().removeAllCachedResponses()
    

    Update for Swift 4.1

    URLCache.shared.removeAllCachedResponses()