One of the main reasons I started this blog is because as a developer, when I defeat a bug, no one really cares. At best, perhaps an end-user cares, but your friends and family do not, even if they may listen patiently. After a few hours of fighting an issue with image caching, I have to share this small triumph with my two subscribers.
I recently released Demotivate HD, which is the pay-for version of Demotivate that costs 99 cents. In the next release, I wanted to incorporate this ImageFilter PhoneGap (Cordova) plugin that I found on another developer’s blog site. Basically this allows you to run your image through a few filters to give it the “Instagram” effect.
After walking the code (I learned a lot about Objective-C though, so it was worth it), I came to the conclusion that the developer did everything correctly. Furthermore, using the built in save function, I could see that the correct image was being passed around and returned properly. Still… something was cached because when I run the program, sometimes (and not always) and old image would return.
How to fix this?
As it turns out, the fix was pretty easy. I generated a random number to tack onto the filename, thus changing the file location each time, eliminating any caching issue. Here’s the code in Objective-C:
int r = arc4random() % 5000;
NSString *random = [NSString stringWithFormat:@"%d", r];
NSString *tPathA = [documentsPath stringByAppendingPathComponent:@"worn"];
NSString *tPathB = [tPathA stringByAppendingString:random];
NSString *filePathB = [tPathB stringByAppendingString:@".jpg"];
Once you setup the new filename, write it as normal.
[imageData writeToFile:filePathB atomically:NO];