【问题标题】:How to load local html file into UIWebView如何将本地 html 文件加载到 UIWebView
【发布时间】:2011-10-27 03:45:15
【问题描述】:

我正在尝试将 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 是空白的。我将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    当您的项目变得更大时,您可能需要一些结构,以便您的 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">标签,那么subfolder中的图片文件myimage.jpg也会被加载并显示出来。

    致谢:https://stackoverflow.com/a/8436281/4769344

    【讨论】:

      【解决方案2】:

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

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

      注意@"manual/index"ma​​nual是我的目录名!! 都是!!!!对不起我的英语不好......

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

      Hola desde 哥斯达黎加。 Ponga los archivos (html y demás recursos) en undirectio (en mi caso lo llamé manual), luego, arrastre y suelte en XCode, sobre "Supporting Files"。 Usted debe seleccionar las opciones "Copy Items if needed" y "Create folder references"。

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

      Presta atención a @"manual/index", ma​​nual es el nombre de mi Directorio!!

      【讨论】:

        【解决方案3】:

        对于 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)
        

        【讨论】:

        • 这不会加载链接文件,例如
        【解决方案4】:

        可能最好使用 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]];
        

        斯威夫特

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

        【讨论】:

        • 那没用,我做了 NSLog(@"%@",htmlFile);只是检查,它说空。
        • 所以这意味着找不到资源。只需检查: NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html"];没有目录
        • 没有 inDirectory 我得到了:iPhone Simulator/4.3.2/Applications/49351078-9423-4A24-8E58-B2A059961097/WebviewTest.app/sample.html 但 html 没有'没有出现在屏幕上它仍然是空的。我错过了别的东西吗?这是示例项目:http://www.box.net/shared/rb05b4ppjnbof1r33gh7
        • 你只需要修复你的 webview 的框架
        • 这个答案有很多票,但似乎已经过时了。使用这种方法不会加载本地图像和 CSS 资产。请参阅this answer
        【解决方案5】:
        [[NSBundle mainBundle] pathForResource:@"marqueeMusic" ofType:@"html"];
        

        可能会迟到,但如果来自pathForResource 的文件是nil,您应该将其添加到Build Phases > Copy Bundle Resources

        【讨论】:

          【解决方案6】:

          这是 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 _ {
                  }
              }
          

          【讨论】:

            【解决方案7】:

            我猜你需要先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];
            }
            

            【讨论】:

              【解决方案8】:

              编辑 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

              【讨论】:

              • 我无法在此页面上获得公认的答案——但这种方法第一次奏效。我认为,自最初的答案以来,iOS 已经继续前进。谢谢。
              • 感谢您的回答。这与接受的答案有什么不同之处在于 HTML 文档工作中的链接。
              • Apple 为了帮助您避免容易受到安全攻击,请务必使用 loadHTMLString:baseURL: 来加载本地 HTML 文件;不要使用 loadRequest:。
              • 接受的答案对我不起作用。谢谢@neal Ehardt,这个答案对我有用。
              • 这仅适用于我的 html 文件不在任何文件夹中
              【解决方案9】:
              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 _ {
                  }
              }
              

              【讨论】:

                【解决方案10】:

                在 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)
                

                【讨论】:

                • 最好使用 let 来测试路径/无文件中的错误:
                【解决方案11】:
                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】:

                  一个简单的复制粘贴代码 sn-p:

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

                  注意:

                  确保检查 html 文件的 目标成员身份,否则将抛出以下异常:-

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

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

                  【讨论】:

                    【解决方案13】:

                    一种使用 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)
                    

                    【讨论】:

                      【解决方案14】:
                      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]]];
                      

                      【讨论】:

                        【解决方案15】:

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

                        【讨论】:

                          【解决方案16】:

                          这里是使用 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 文件

                          【讨论】:

                            【解决方案17】:

                            通过这个,您可以将项目 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]]];
                            

                            也许这对你有用。

                            【讨论】:

                            • 这与我所做的相同,唯一的区别是您正在以编程方式创建 webView。不过还是谢谢
                            • 你通过NSLog获取该html文件检查的路径。
                            • 应检查 html 文件的目标成员身份,否则将引发以下异常:-由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'*** -[NSURL initFileURLWithPath:isDirectory:]:零字符串参数'
                            【解决方案18】:

                            可能是您的 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];
                            

                            【讨论】:

                              猜你喜欢
                              • 2011-06-06
                              • 1970-01-01
                              • 2013-01-18
                              • 1970-01-01
                              • 1970-01-01
                              • 2011-01-02
                              • 1970-01-01
                              • 1970-01-01
                              • 2014-12-26
                              相关资源
                              最近更新 更多