首页 文章

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

提问于
浏览
161

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

17 回答

  • 5

    可能最好使用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 调用是否找到了资源 .

  • 262
    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 _ {
        }
    }
    
  • 3

    EDIT 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 .

  • 3

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

    这可能对你有用 .

  • 4

    我想你需要 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];
    }
    
  • 0

    A Simple Copy-Paste code snippet:

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

    Note:

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

    enter image description here

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

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

  • 3
    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]]];
    
  • 89

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

    可能是你的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

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

  • 0

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

  • 39

    使用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)
    
  • 9
    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)
    
  • 2
    [[NSBundle mainBundle] pathForResource:@"marqueeMusic" ofType:@"html"];
    

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

    enter image description here

  • 3

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

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

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

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

    注意 @"manual/index"manual 是我的目录的名称!!这都是!!!!对不起,我的英语不好...

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

    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"manual es el nombre de mi directorio !!

相关问题