0

I have an NSString containing some HTML. I’m trying to pre-load that HTML, including any external image links inside it. So, to clarify: I have just HTML, and I need to basically load it, grab its images, and cache that data.

I can do this with a live website using the following code:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0], @"index.html"];
NSURL *url = [NSURL URLWithString:@"http://www.google.co.uk"];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];

But this won’t work without an NSURL. I’m wondering if I can make an NSURL somehow from this string of HTML, and substitute it in the URLWithString: method here.

So, question: can I take some local HTML inside an NSString and turn that into an NSURL, so that I can feed it into the code above, and save the both the HTML and any images it links to?

Luke
  • 9,512
  • 15
  • 82
  • 146

2 Answers2

1

The question you are asking makes absolutely no sense.

A URL is a pointer to the location of a resource online. In this context a html file. You can not make one into the other.

I suggest you create a UIWebView, load the string into that, have it render and cache the result.

[webView loadHTMLString:@"data" baseURL:nil];

I believe it will need to be actually place on the screen for it to render, so make it an invisible 1 X 1 pixel square and it should be fine. Then when the didFinishLoading fires. Cache the result

Simon McLoughlin
  • 8,293
  • 5
  • 32
  • 56
  • That’s what I’m doing at present when they access the content, but if they do that while offline, I need to have persisted the message they’ll see, including its images. Can I tell an invisible `webView` to load it, one that hasn’t been added to a view? And from there, is there a means of telling the `webView` to cache its contents after it finishes loading? – Luke Jan 14 '15 at 11:33
  • Ah, you edited while I was writing the above ^ I’ll look into how to cache the contents of the web view. Any tips on how that’s done? – Luke Jan 14 '15 at 11:34
  • @lukech yes, by googling it: http://stackoverflow.com/questions/992348/reading-html-content-from-a-uiwebview – Simon McLoughlin Jan 14 '15 at 11:36
0

Yes, you can. You would have to parse the links out of HTML yourself. Real world HTML is not XML compliant, so a quick and dirty way to achieve your goals would be to treat HTML as text and parse links out using a regular expression library.