How would you create a new local HTML file into a UIWebView on iOS?
html, ios, local, uiwebview
Solution
You can build the HTML in a `NSString` like so:
// get user input
NSString *userText = @"Hello, world!";
// build the HTML
NSString *html = [NSString stringWithFormat:@"<html><body>%@</body><html>", userText];
// build the path where you're going to save the HTML
NSString *docsFolder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filename = [docsFolder stringByAppendingPathComponent:@"sample.html"];
// save the NSString that contains the HTML to a file
NSError *error;
[html writeToFile:filename atomically:NO encoding:NSUTF8StringEncoding error:&error];
Clearly I'm just setting the `userText` to some literal, but you could obviously let the user type it into a `UITextView` and grab it from there.
You can then load the HTML into a web view with:
[self.webView loadHTMLString:html baseURL:nil];
or with:
NSURL *url = [NSURL fileURLWithPath:filename];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
Problem
First I would like to point out I'm very new to web development and more comfortable with iOS development, so excuse me if there's something fundamental I'm not understanding. I've seen how you can place an HTML file into your apps directory and load it into a web view (Example). This is great, but how can you create a new local HTML file within the app? Such that the user can create a new html file to type in, and then store it (basic document style app functionality). Perhaps with some sort of Javascript (I'm not too familiar with such Javascript)?