我试图将一个html文件加载到我的UIWebView中,但它不起作用.现在是阶段:我的项目中有一个名为html_files的文件夹.然后,我在界面构建器中创建了一个WebView,并在viewController中为它分配了一个插座.这是我用来附加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 has few changes:

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相关问答推荐

SwiftUI ScrollView中的默认空间

如何在SwiftUI中扩展 colored颜色 超出顶部边缘

底部导航栏在iOS上浮动

如何从Windows PC在iPhone上安装Flutter 应用程序

快速相机放大手势不能正常工作

当S没有身体时该如何处理

如何在后台显示 Swift UI 中的通讯通知?

在自定义 ButtonStyle 中修改形状 colored颜色

SwiftUI - 如何从主题感知命名 colored颜色 中获取正确的 RGB 值?

iOS - 判断开发者模式是否开启 (Swift)

我需要二进制文件来进行 App Store 应用程序传输吗?

SwiftUI 文本字段代理绑定代码忽略空格不起作用?

检测 iPhone 应用程序中是否存在摄像头?

如何启用滑动以删除 TableView 中的单元格?

故事板中的 colored颜色 与 UIColor 不匹配

判断密钥是否存在于 NSDictionary 中

NSURLSession:如何增加 URL 请求的超时时间?

iPhone:什么是 WWDR 中级证书?

UICollectionView:必须用非零布局参数初始化

你如何以编程方式从视图控制器中画一条线?