1

I want to cache an image I download from a URL in the local filesystem.

What I don't know, is how can I create from the URL a NSString that is compatible with the characters the iOS file system supports. For instance, if I try to create a file with a : in the name, it will fail.

What steps should I follow to create this NSString? Is a simple hash the best way to go? If so, what hash routine is available in iOS that I can use?

2 Answers 2

1

I'd use hashing:

  • it'll make for much more readable file names
  • you avoid problems with file name length

md5 should be perfectly fine for your purposes. Unfortunately, the ios5-sdk contains only a C-String function for this:

CC_MD5(in, in_len, out);

The function is contained in <CommonCrypto/CommonDigest.h>, there are other hash functions there, too.

You can find infos on how to wrap this up in a function that takes/returns an NSString here.

0

The following code belongs to ZDS_Shared. resolveLocalURLForRemoteURL accepts a remote URL and returns a URL pointing to the file on the iOS filesystem. The filename will be an alphanumeric string that doesn't resemble the original URL, but that shouldn't be a problem.

https://github.com/ZarraStudios/ZDS_Shared/blob/master/ZSAssetManager.m#L185

- (NSURL*)resolveLocalURLForRemoteURL:(NSURL*)url
{
  if (!url) return nil;

  NSString *filename = [[url absoluteString] zs_digest];
  NSString *filePath = [[self cachePath] stringByAppendingPathComponent:filename];

  return [NSURL fileURLWithPath:filePath];
}

https://github.com/ZarraStudios/ZDS_Shared/blob/master/NSString%2BZSAdditions.m#L38

// NSString category
- (NSString*)zs_digest
{
  const char *cstr = [self cStringUsingEncoding:NSASCIIStringEncoding];
  return [[NSData dataWithBytes:cstr length:strlen(cstr)] zs_digest];
}

https://github.com/ZarraStudios/ZDS_Shared/blob/master/NSData%2BZSAdditions.m#L38

// NSData category
- (NSString*)zs_digest
{
  uint8_t digest[CC_SHA1_DIGEST_LENGTH];

  CC_SHA1([self bytes], [self length], digest);

  NSMutableString* outputHolder = [[NSMutableString alloc] initWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];

  for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
    [outputHolder appendFormat:@"%02x", digest[i]];
  }

  NSString *output = [outputHolder copy];
  MCRelease(outputHolder);

  return [output autorelease];
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.