Search code examples
iosios7uiwebview

HTML Link from within a local HTML file in a UIWebView


Very new to XCode here

Basically, we have an app dependent on the UIWebView. When there is a valid network connection, we load a mobile web page into the UIWebView, if there is no connection, we will load a local version of the html web page. My scenario has to do with the offline or limited network connection scenario. When this offline scenario does occur, I am able to load my local html file just fine using the answer from this thread:

Load resources from relative path using local html in uiwebview

My problem comes in when click on a simple html link (which is also within my local app directory) within the local html file that is loaded. I have tried these, but when I click the link, nothing occurs, the link does not take me anywhere and the simulator will only allow me to copy the text:

<a href="file:///Sample.html">
<a href="file://Sample.html">
<a href="Sample.html">
<a href="/Sample.html">
<a href="Testing/Sample.html">

The sample.html webpage is in the same directory as the initial loaded html page. Not sure where I am going wrong, obviously missing something simple.


Solution

  • I suggest you re-examine your directory hierarchy. The behavior you are describing is what happens when the link you are trying to navigate to does not exist on the local device. I ran the following small test:

    Added a Webview to a view controller and loaded page1.html

    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 10, 320, 300)];
    [self.view addSubview:webView];
    
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"page1" withExtension:@"html"];
    NSString *html = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    NSURL *baseUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
    [webView loadHTMLString:html baseURL:baseUrl];
    

    page1.html

    <html>
    <body>
        <h1>Page 1</h1>
        <a href="page2.html">Go to Page2</a>
    </body>
    </html>
    

    page2.html

    <html>
        <body>
            <h1>Page 2</h1>
            <a href="page1.html">Back to Page 1</a>
        </body>
    </html>
    

    Image of the project Structure

    Image of the project structure

    The end result is, that it works. Clicking takes you from page 1 to page 2 and back again all using local files. If we change the link to:

    <a href="page3.html"></a>

    which does not exist, you get the same behavior you are experiencing. That is you can only cut and copy and not actually go to the link.

    enter image description here enter image description here