Saving HTML and Other Text Files to the Documents Directory
First, you need to know the path to your documents directory:
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
You can create documents and directories there up to the limits of the device storage. Be aware, however, that only files in the root will show up in iTunes Document Sharing.
So, if you have a string htmlContent
and a string htmlFilename
, you can save it. Do pay attention to the encoding you're using; the encoding in the HTML header and meta tags (if present) should match the encoding used here.
NSString *htmlPath = [documentsPath stringByAppendingPathComponent:htmlFilename];
[htmlContent writeToFile:htmlPath atomically:NO encoding:NSUTF8StringEncoding error:nil];
Displaying HTML Files Within Your App
You can display HTML in a UIWebView
. Assuming you have one called webView
, you can display any NSURL
object in it:
NSURL *stackOverflowAddress = [NSURL URLWithString:@"http://www.stackoverflow.com"];
[[self webView] loadRequest:[NSURLRequest requestWithURL:stackOverflowAddress]];
This can include the file you just wrote:
NSURL *htmlURL = [NSURL fileURLWithPath:htmlPath];
[[self webView] loadRequest:[NSURLRequest requestWithURL:htmlURL]];
Or, you can put a string into it directly:
[[self webView] loadHTMLString:htmlContent baseURL:nil];
If you use a UIWebView
for a lot of your functionality, take the time to read the UIWebViewDelegate Protocol Reference.
Opening HTML in Safari
It is also possible to tell your application to open URLs elsewhere. This will usually result in Safari opening. However, because Safari does not have access to your app's document directory, it cannot display documents while they are saved locally.
[[UIApplication sharedApplication] openURL:stackoverflowAddress];