1

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?

4

1 に答える 1

1

If you do proper networking, NSURLCache handles caching of images just fine automatically.

However, I got the feeling that you aren’t really interested in caching, but in (more or less permanently) storing images.

In that case, build a proper model for your app.

Because you don’t tell us what the images you want to be storing are for, I cannot be more helpful than this:

If you’re on iOS 5+/OS X 10.7+, you can use NSAttributeDescription’s allowsExternalBinaryDataStorage setting to have the NSSQLiteStoreType handle naming, creating, retrieving, updating, and deleting the backing files for the image data transparently on your behalf.

If you have to support older OS versions, you can still use external storage through a transient attribute. Your entity description then has to have an attribute for the name of the data-file, though. In that situation, the SHA-1 (available through the CommonCrypto framework) of the image’s data will provide for a good file name.


Aside

If you’ve found that code in an answer on Objective-C, downvote it, and delete that code above:

-[NSString stringByAddingPercentEscapesUsingEncoding:], and CFURLCreateStringByAddingPercentEscapes do exactly what they (or their docs) say.

于 2012-10-17T06:38:26.940 に答える