What would be a good way to pick cache file names for images downloaded from internet for caching purpose to ensure that no matter what the URL is we got valid file name?
We often pick images from the net. It's often useful to store those images in temporary cache so we don't keep downloading the same image again and again.
So I suppose, I would need a cacheFileName. It should be a function of the URL. However, it must not contain special characters like :, /, &
In other words, it has to be a valid file name.
What would be the way to do so?
I can make some my self. Perhaps I can use URLEncode which seems to do just fine. However, I wonder, if there are consideration I missed.
This is the current Code I use:
- (NSString *) URLEncodedString {
NSMutableString * output = [NSMutableString string];
const char * source = [self UTF8String];
int sourceLen = strlen(source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = (const unsigned char)source[i];
if (false && thisChar == ' '){
[output appendString:@"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:@"%c", thisChar];
} else {
[output appendFormat:@"%%%02X", thisChar];
}
}
return output;
}
It's taken from some great answer in stackOverflow which I have forgotten.
I wonder if the result of this function will always get a valid file name. Does anyone has better file name generator?