[ios] How to load local html file into UIWebView

I'm trying to load a html file into my UIWebView but it won't work. Here's the stage: I have a folder called html_files in my project. Then I created a webView in interface builder and assigned an outlet to it in the viewController. This is the code I'm using to append the html file:

-(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];
}

That won't work and the UIWebView is blank. I'd appreciate some help.

This question is related to ios objective-c iphone cocoa-touch uiwebview

The answer is


Make sure "html_files" is a directory in your app's main bundle, and not just a group in Xcode.


For Swift 3 and 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)

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]]];

May be your HTML file doesn't support UTF-8 encoding, because the same code is working for me.

Or u can also these line of code:

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];

I guess you need to allocate and init your webview first::

- (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];
}

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

It may be late but if the file from pathForResource is nil you should add it in the Build Phases > Copy Bundle Resources.

enter image description here


Put all the files (html and resources)in a directory (for my "manual"). Next, drag and drop the directory to XCode, over "Supporting Files". You should check the options "Copy Items if needed" and "Create folder references". Next, write a simple code:

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

Attention to @"manual/index", manual is the name of my directory!! It's all!!!! Sorry for my bad english...

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

Hola desde Costa Rica. Ponga los archivos (html y demás recursos) en un directorio (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", manual es el nombre de mi directorio!!


by this you can load html file which is in your project Assets(bundle) to 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]]];

may be this is useful to you.


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)

Here's 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 _ {
        }
    }

A new way to do this using swift. The UIWebView is no more and WKWebView is the new class to load web pages, which ensures the Safari features to the web view.

    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)

Here the way the working of HTML file with Jquery.

 _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];

You can use either the requests to call the HTML file in your UIWebview


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

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:

Make sure the html file's Target membership is checked otherwise following exception will get thrown :-

enter image description here

Terminating app due to uncaught exception

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


EDIT 2016-05-27 - loadRequest exposes "a universal Cross-Site Scripting vulnerability." Make sure you own every single asset that you load. If you load a bad script, it can load anything it wants.

If you need relative links to work locally, use this:

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

The bundle will search all subdirectories of the project to find my.html. (the directory structure gets flattened at build time)

If my.html has the tag <img src="some.png">, the webView will load some.png from your project.


When your project gets bigger, you might need some structure, so that your HTML page can reference files located in subfolders.

Assuming you drag your html_files folder to Xcode and select the Create folder references option, the following Swift code ensures that the WKWebView supports also the resulting folder structure:

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

This means that if your sample.html file contains an <img src="subfolder/myimage.jpg"> tag, then the image file myimage.jpg in subfolder will also be loaded and displayed.

Credits: https://stackoverflow.com/a/8436281/4769344


In Swift 2.0, @user478681's answer might look like this:

    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)

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to cocoa-touch

Include of non-modular header inside framework module Move textfield when keyboard appears swift Create space at the beginning of a UITextField Navigation bar with UIImage for title Generate a UUID on iOS from Swift How do I write a custom init for a UIView subclass in Swift? creating custom tableview cells in swift How would I create a UIAlertView in Swift? Get current NSDate in timestamp format How do you add an in-app purchase to an iOS application?

Examples related to uiwebview

How to display .svg image using swift Can I set the cookies to be used by a WKWebView? How to Migrate to WKWebView? iOS JavaScript bridge How to load local html file into UIWebView Load resources from relative path using local html in uiwebview Clearing UIWebview cache How to determine the content size of a UIWebView? UIWebView open links in Safari Can we open pdf file using UIWebView on iOS?