title: iOS - Caching remote image
body: <p>I am trying to cache images from the web to prevent excessive web requests to save battery and data. The basic idea is:</p>
  
  <ol>
  <li>Generate the string of the File's Location </li>
  <li>If the file exists then load it from the file</li>
  <li>If its not in existence (todo: or if the file is older than a day) then download the image from the web. Save it and load it.</li>
  </ol>
  
  <p>However my code isn't working and I can't figure out why?</p>
  
  <pre><code>// imagesFileName has been correctly generated as as imageURL
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                       NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];
  NSString *imagesLibraryPath = [documentsDirectory stringByAppendingPathComponent:@"Images"];
  NSString *imagePath = [imagesLibraryPath stringByAppendingPathComponent:imageFileName];
  
  
  // Do We Have the icon in cache?
  if (![[NSFileManager defaultManager] fileExistsAtPath:iconPath]) {
      // File Doesn't Exist - Load Image From URL
      NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imagesURL]];
  
      // Save Image
      [imageData writeToFile:imagePath atomically:YES];
  
  
      NSLog(@"Downloading &amp; Importing Image");
      return [UIImage imageWithData:imageData];
  } else {
      // Load the Image From The File But Update If Needed
      NSLog(@"Loading Image From Cache");
      return [UIImage imageWithContentsOfFile:imagePath];
  }
  </code></pre>