What does loadHTMLString:baseURL:

10,390

Solution 1

I am pretty certain that the baseURL is used just like in regular web pages to properly load ressources that are referenced using relative links. Now the question is, how to set that base URL to a particular folder in the app directory.

Solution 2

This is how mainly content is loaded in a webView. either from a local html file or through a url.

//this is to load local html file. Read the file & give the file contents to webview.
[webView loadHTMLString:someHTMLstring baseURL:[NSURL URLWithString:@""]]; 

//if webview loads content through a url then 
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]]]

Solution 3

- (void) loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL; 

is used to load local HTML file, parameter string means content of html file, if your HTML file contains some href tag with relative path, you should set the parameter baseUrl with the base address of the HTML file, or set it nil.

NSString *cachePath = [self cachePath];
NSString *indexHTMLPath = [NSString stringWithFormat:@"%@/index.html", cachePath];
if ([self fileIsExsit:indexHTMLPath]) {
    NSString *htmlCont = [NSString stringWithContentsOfFile:indexHTMLPath
                                                            encoding:NSUTF8StringEncoding
                                                               error:nil];
    NSURL *baseURL = [NSURL fileURLWithPath:cachePath];
    [self.webView loadHTMLString:htmlCont baseURL:baseURL];
}

- (NSString *)cachePath
{
    NSArray* cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [cachePath[0] stringByAppendingPathComponent:@"movie"];
}
Share:
10,390
user1075871
Author by

user1075871

Updated on July 02, 2022

Comments

  • user1075871
    user1075871 almost 2 years

    I new to iOS programming and tried to figure out what loadHTMLString:baseURL: really does, but I can't find a satisfying explanation. The site of Apple just says:

    Sets the main page content and base URL.

    Can someone please explain this in a more detailed way to me?

  • MACMAN
    MACMAN over 9 years
    If I want to load a local file I can replace @"" with @index.html. right?