我怎样才能加载一个本地的HTML文件到UIWebView?

我们如何加载我们自己的HTML文件到UIWebView?

下面的代码将在您的项目文件夹中加载一个名为index.html的HTML文件:

 [WebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]]; 

科迪格雷是正确的,但也有这样的方式:

 // Load the html as a string from the file system NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]; NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; // Tell the web view to load it [WebView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]]; 

如果您在加载之前需要编辑html,这非常有用。

迅速

  guard let path = NSBundle.mainBundle().pathForResource("index", ofType: "html") else { return } let url = NSURL(fileURLWithPath: path) self.webview.loadRequest(NSURLRequest(URL:url)) 

通过使用下面的代码,你可以在WebView中加载一个HTML。Web是Web视图的obj和inde

 Web.delegate = self; [Web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]]; 

Swift版本2.1

 // load html to String with Encoding let path = NSBundle.mainBundle().pathForResource("policy", ofType: "html") do { let fileHtml = try NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding) webView.loadHTMLString(fileHtml as String, baseURL: nil) } catch { } 

苹果的文档build议使用loadHTMLString:baseURL: ::

使用loadHTMLString:baseURL:方法开始加载本地HTML文件,或使用loadRequest:方法开始加载Web内容。 使用stopLoading方法停止加载,并使用加载属性来查看Web视图是否正在加载。

loadHTMLString:baseURL:文档提供了进一步的推理:

为了帮助您避免受到安全攻击,请务必使用此方法加载本地HTML文件; 不要使用loadRequest :.

这可能有帮助: https : //stackoverflow.com/a/29741277

 NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"privacy-Policy" ofType:@"html" inDirectory:nil]; NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile]; [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];