【问题标题】:How would you create a new local HTML file into a UIWebView on iOS?你将如何在 iOS 上的 UIWebView 中创建一个新的本地 HTML 文件?
【发布时间】:2013-03-22 01:55:01
【问题描述】:
首先我想指出我对 Web 开发非常陌生,并且对 iOS 开发更熟悉,所以如果有一些我不理解的基本内容,请原谅。
我已经了解了如何将 HTML 文件放入您的应用程序目录并将其加载到 Web 视图中 (Example)。这很好,但是如何在应用程序中创建新的本地 HTML 文件?这样用户可以创建一个新的 html 文件来输入,然后存储它(基本的文档样式应用程序功能)。也许使用某种 Javascript(我对这种 Javascript 不太熟悉)?
【问题讨论】:
标签:
html
ios
uiwebview
local
【解决方案1】:
您可以像这样在NSString 中构建 HTML:
// 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];
显然我只是将userText 设置为一些文字,但您显然可以让用户将其键入UITextView 并从那里获取。
然后您可以使用以下命令将 HTML 加载到 Web 视图中:
[self.webView loadHTMLString:html baseURL:nil];
或与:
NSURL *url = [NSURL fileURLWithPath:filename];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];