user1173142
user1173142

Reputation: 553

How to use HTML file in iPhone

I want to use an HTML file in my code currently I am using following line of code:

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

But the problem which I am facing is: the HTML Page contains some images, and all that images are in a folder in my project but I am not able to see that images in the HTML page at run time.

Upvotes: 2

Views: 2029

Answers (2)

Nimit Parekh
Nimit Parekh

Reputation: 16864

Here the possible ways to use HTML into the project, Following code for the load HTML file into xcode project

Example 1, loading the content from a URLNSURL

    NSURL *url = [NSURL URLWithString:@"http://google.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];

Example 2, loading the content from a string

    NSString *HTMLData = @"<h1>Hello this is a test</h1>";
    [webView loadHTMLString:HTMLData baseURL:nil];

Example 3, loading the content from a local file

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html"];
NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
[webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];

Hope this code helping to develop a application

Upvotes: 3

ale84
ale84

Reputation: 1406

You can set the baseURL to your resource folder, where your images are located:

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"htm" inDirectory:nil];
NSString *htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
NSString *resourcePath = [[NSBundle mainBundle]resourcePath];
NSURL *baseUrl = [[NSURL alloc]initFileURLWithPath:resourcePath];
[self.myWebView loadHTMLString:htlmString baseURL:baseUrl];

Upvotes: 4

Related Questions