0

Hello I have a html string, with tags for every image.

I can extract the url of every image, but what I want is to save those images in the device, and then replace each one's image url with the corresponding path from my sandbox and then display them via UIWebView.

Any ideas how do I do that?

Thank you!

DevFly
  • 413
  • 3
  • 15

1 Answers1

1

Well if you have the URL for an image, you can save it like this

NSData *imageData = [NSData dataWithContentsOfURL:[NSURL urlWithString:string]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"MyFile"];
[imageData writeToFile:filePath atomically:YES];

To replace the URLs in the HTML string simply use the method

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement

Vlad
  • 26
  • 3
  • Is there more efficient method, for a lot of images? I have to do that for every image.Besides there is cool way to get images from sandbox in webview - http://stackoverflow.com/questions/747407/using-html-and-local-images-within-uiwebview Thanks for the answer! – DevFly Aug 30 '12 at 06:26
  • I don't think there is. You can always do it in the background and add a loading widget or something if it's required. As for the sandbox thing, if you have the , you proceed as described in that post you linked and you use the method I mentioned to replace yourURL with the name of the image in your project. – Vlad Aug 30 '12 at 06:33
  • Oh and don't forget to add an extra set of quotes for the filename – Vlad Aug 30 '12 at 06:34
  • Can UICollectionView help here? – nielsbot Aug 30 '12 at 06:37
  • I haven't used UICollectionView yet, but that's just a way of presenting a set of views. If you think that it better suits your needs, go ahead and use it (iOS 6 only though). It's got nothing to do with saving images to local storage however. – Vlad Aug 30 '12 at 06:42
  • Vlad just one question. What does NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"MyFile"]; do? Is it directory like Documents/MyFile/ or it's a file like Documents/MyFile.png It's a little bit frustrating. Thanks – DevFly Aug 30 '12 at 06:56
  • It's the path to your file i.e. Documents/myImage.png. Sorry wasn't too clear on that. – Vlad Aug 30 '12 at 06:57
  • Thanks, how do I save it to custom directory inside Documents? I have tried NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"MyDir/MyFile"]; and it doesn't save it. – DevFly Aug 30 '12 at 07:18