我怎样才能加载一个本地的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:@""]];
- MPNowPlayingInfoCenter是否与AVAudioPlayer兼容?
- 苹果外部附件(蓝牙)只适用于MFI设备?
- 使UITextView父项成为它自己的inputAccessoryView
- 什么是iOS 5 SDK中的容器视图?
- PFObject不反映“parsing数据浏览器”中的“成功”保存的更改
- iOS 8 .scheduledLocalNotifications为空
- 如何使用MFMailComposeViewController在电子邮件正文中添加图像
- 我可以在不使用Xcode IDE的情况下构buildiOS的静态库吗?
- Swift UIApplication.setStatusBarStyle不起作用