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

时间:2011-08-15 09:08:06

标签: ios objective-c iphone cocoa-touch uiwebview

我正在尝试将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是空白的。我很感激一些帮助。

18 个答案:

答案 0 :(得分:263)

可能最好使用NSString并加载html文档,如下所示:

<强>目标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]];

<强>夫特

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电话是否找到了资源。

答案 1 :(得分:89)

编辑2016-05-27 - loadRequest exposes "a universal Cross-Site Scripting vulnerability."确保您拥有自己加载的每一项资产。如果你加载了一个糟糕的脚本,它可以加载它想要的任何东西。

如果您需要相关链接在本地工作,请使用:

NSURL *url = [[NSBundle mainBundle] URLForResource:@"my" withExtension:@"html"];
[webView loadRequest:[NSURLRequest requestWithURL:url]];

捆绑包将搜索项目的所有子目录以查找my.html。 (目录结构在构建时变平)

如果my.html的代码为<img src="some.png">,则webView会从您的项目中加载some.png

答案 2 :(得分:39)

通过这个,您可以将项目Assets(bundle)中的html文件加载到webView。

 UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];

可能对你有用。

答案 3 :(得分:9)

我想您需要allocate并首先初始化您的webview

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

    [super viewDidLoad];
}

答案 4 :(得分:8)

简单的复制粘贴代码段:

-(void)LoadLocalHtmlFile:(NSString *)fileName onWebVu:(UIWebView*)webVu
{
    [webVu loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:fileName ofType:@"html"]isDirectory:NO]]];
}

注意:

确保检查html文件的目标成员资格,否则将抛出异常: -

enter image description here

由于未捕获的异常而终止应用

'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:isDirectory:]: nil string parameter'

答案 5 :(得分:6)

对于Swift 3和Swift 4:

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

答案 6 :(得分:5)

UIWebView *web=[[UIWebView alloc]initWithFrame:self.view.frame];
    //[self.view addSubview:web];
    NSString *filePath=[[NSBundle mainBundle]pathForResource:@"browser_demo" ofType:@"html" inDirectory:nil];
    [web loadRequest:[NSURLRequest requestWhttp://stackoverflow.com/review/first-postsithURL:[NSURL fileURLWithPath:filePath]]];

答案 7 :(得分:4)

可能是您的HTML文件不支持UTF-8编码,因为相同的代码对我有效。

或者您也可以使用这些代码:

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"Notes For Apple" ofType:@"htm" inDirectory:nil];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[WebView loadHTMLString:htmlString baseURL:nil];

答案 8 :(得分:4)

这里是使用Jquery运行HTML文件的方式。

 _webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 568)];
    [self.view addSubview:_webview];

    NSString *filePath=[[NSBundle mainBundle]pathForResource:@"jquery" ofType:@"html" inDirectory:nil];

    NSLog(@"%@",filePath);
    NSString *htmlstring=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

    [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
                         or
    [_webview loadHTMLString:htmlstring baseURL:nil];

您可以使用请求在UIWebview中调用HTML文件

答案 9 :(得分:3)

使用swift执行此操作的新方法。 UIWebView已不复存在,WKWebView是加载网页的新类,可确保Safari功能进入Web视图。

    import WebKit

    let preferences = WKPreferences()
    preferences.javaScriptCanOpenWindowsAutomatically = false

    let configuration = WKWebViewConfiguration()
    configuration.preferences = preferences

    let webView = WKWebView(frame: self.view.bounds, configuration: configuration)
    let request = NSURLRequest(URL: NSURL(string: "http://nshipster.com"))
    webView.loadRequest(request)

答案 10 :(得分:3)

[[NSBundle mainBundle] pathForResource:@"marqueeMusic" ofType:@"html"];

可能会延迟,但如果pathForResource中的文件为nil,则应将其添加到Build Phases > Copy Bundle Resources

enter image description here

答案 11 :(得分:3)

Swift iOS:

 // get server url from the plist directory
        var htmlFile = NSBundle.mainBundle().pathForResource("animation_bg", ofType: "html")!
        var htmlString = NSString(contentsOfFile: htmlFile, encoding: NSUTF8StringEncoding, error: nil)
        self.webView.loadHTMLString(htmlString, baseURL: nil)

答案 12 :(得分:3)

确保“html_files”是应用主要包中的目录,而不仅仅是Xcode中的一个目录。

答案 13 :(得分:2)

这是Swift 3:

    if let htmlFile = Bundle.main.path(forResource: "aa", ofType: "html"){
        do{
            let htmlString = try NSString(contentsOfFile: htmlFile, encoding:String.Encoding.utf8.rawValue )
            messageWebView.loadHTMLString(htmlString as String, baseURL: nil)
        }
        catch _ {
        }
    }

答案 14 :(得分:1)

if let htmlFile = NSBundle.mainBundle().pathForResource("aa", ofType: "html"){
    do{
        let htmlString = try NSString(contentsOfFile: htmlFile, encoding:NSUTF8StringEncoding )
        webView.loadHTMLString(htmlString as String, baseURL: nil)
    }
    catch _ {
    }
}

答案 15 :(得分:0)

在Swift 2.0中,@ user478681的答案可能如下所示:

    let HTMLDocumentPath = NSBundle.mainBundle().pathForResource("index", ofType: "html")
    let HTMLString: NSString?

    do {
        HTMLString = try NSString(contentsOfFile: HTMLDocumentPath!, encoding: NSUTF8StringEncoding)
    } catch {
        HTMLString = nil
    }

    myWebView.loadHTMLString(HTMLString as! String, baseURL: nil)

答案 16 :(得分:0)

将所有文件(html和资源)放在一个目录中(对于我的“手册”)。接下来,通过“Supporting Files”将目录拖放到XCode。您应该选中“如果需要,复制项目”和“创建文件夹引用”选项。接下来,编写一个简单的代码:

NSURL *url = [[NSBundle mainBundle] URLForResource:@"manual/index" withExtension:@"html"];
[myWebView loadRequest:[NSURLRequest requestWithURL:url]];

注意@"manual/index"手册是我的目录的名称!! 这都是!!!!抱歉我的英语不好......

=============================================== ========================

Hola desde哥斯达黎加。 Ponga los archivos(htmlydemásreecursos)en un directorio(en mi casolollamémanual),luego,arrastre y suelte en XCode,sobre“Supporting Files”。 Usted debe seleccionar las opciones“需要时复制项目”y“创建文件夹参考”。

NSURL *url = [[NSBundle mainBundle] URLForResource:@"manual/index" withExtension:@"html"];
[myWebView loadRequest:[NSURLRequest requestWithURL:url]];

Prestaatencióna@"manual/index"手册 es el nombre de mi directorio !!

答案 17 :(得分:0)

当您的项目变大时,您可能需要某种结构,以便您的HTML页面可以引用位于子文件夹中的文件。

假设您将html_files文件夹拖到Xcode并选择创建文件夹引用选项,以下 Swift 代码可确保WKWebView支持以及产生的文件夹结构:

import WebKit

@IBOutlet weak var webView: WKWebView!

if let path = Bundle.main.path(forResource: "sample", ofType: "html", inDirectory: "html_files") {
    webView.load( URLRequest(url: URL(fileURLWithPath: path)) )
}

这意味着,如果您的sample.html文件包含<img src="subfolder/myimage.jpg">标签,则myimage.jpg中的图像文件subfolder也将被加载并显示。

积分:https://stackoverflow.com/a/8436281/4769344