ios - 如何将本地 html 文件加载到 UIWebView

标签 ios objective-c iphone cocoa-touch uiwebview

我正在尝试将 html 文件加载到我的 UIWebView 中,但它不起作用。这是阶段:我的项目中有一个名为 html_files 的文件夹。然后我在界面生成器中创建了一个 webView,并在 viewController 中为其分配了一个 socket 。这是我用来附加 html 文件的代码:

-(void)viewDidLoad
{
    NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html" inDirectory:@"html_files"];
    NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
    [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];
    [super viewDidLoad];
}

这不起作用,UIWebView 是空白的。我将不胜感激。

最佳答案

可能最好使用 NSString 并按如下方式加载 html 文档:

Objective-C

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[webView loadHTMLString:htmlString baseURL: [[NSBundle mainBundle] bundleURL]];

swift

let htmlFile = NSBundle.mainBundle().pathForResource("fileName", ofType: "html")
let html = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding)
webView.loadHTMLString(html!, baseURL: nil) 

Swift 3 有一些变化:

let htmlFile = Bundle.main.path(forResource: "intro", ofType: "html")
let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
webView.loadHTMLString(html!, baseURL: nil)

你试过了吗?

还要检查 pathForResource:ofType:inDirectory 调用是否找到了资源。

关于ios - 如何将本地 html 文件加载到 UIWebView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7063276/

相关文章:

ios - 如何修复“WKWebViewManager.evaluateJavaScript 不是函数”

iphone - IOS UiView动画在ios 5和ios 6设备上产生不同的效果

javascript - HTML5 持久跟踪地理位置

iphone - 数据库在 Sqlite 中被锁定

ios - Alamofire 无法访问 json 响应的键

ios - SwiftEventBus注销swift

iphone - 如何在不同方向设置 UILabel 的位置

ios - 移除 View Controller 底部的灰色条 - iOS

ios - 添加后 GMSMarker 未显示在 map 上

ios - 如何检测iPhone是否连接到任何蓝牙设备?