views:

46

answers:

3

I have the following innocent looking code (index.html), but it doesnt load the code.js file. It works well if I copy / paste the contents of the file in the html page. Both index.html and code.js files are in the same directory. This is the code snippet. Any help would be great.

index.html :

<html>
<head>
<script type="text/javascript" src="code.js"></script>
</head> 
<body onload="drawImage()">
</body>
</html>

ViewController.m:

- (void)viewDidLoad {
    [super viewDidLoad];
 // load the first webpage
 [homePageWebView loadRequest:[NSURLRequest requestWithURL:[NSURLfileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index"ofType:@"html"] isDirectory:NO]]];
}
A: 

You need to read the html file into a string and set the baseURL when loading so relative paths can be understood.

NSError* error;

NSString* html = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"] encoding:NSASCIIStringEncoding error:&error];

    [webview loadHTMLString:html baseURL:[self getBaseURL]];

    - (NSURL*) getBaseURL {
        NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
        NSRange r = [path rangeOfString:@"/" options:NSBackwardsSearch];
        path = [path substringToIndex:r.location];

        path = [path stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
        path = [path stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
        path = [NSString stringWithFormat:@"file:/%@//",path];
        return  [NSURL URLWithString:path];
    }

Something like that should work for you.

skorulis
I think if you set base in the header of the HTML document, it will work too, and will not require any additional code.
spbfox
How do you set the base header for a local file. It tried by putting <base href="./"> and <base href="/"> in the <head>, but still doesnt work. Can you give me an example please.
Amarsh
How could you know what the base URL of the file is going to be ahead of time? It would change depending on where it was deployed.
skorulis
oh so sorry, it wasnt clear above, all the files are in the resource bundle, and hence local to the app.
Amarsh
This should not be needed. Loading a local `file://` url will work fine.
Squeegy
+1  A: 

I have found that Xcode thinks that the js file needs to be compiled.

Open the project in Xcode. Go to "Targets" and look in "Compile Sources". If you see your js file in that folder, move it to the "Copy Bundle Resources" folder and delete it from the "Compile Sources" folder.

Delete the app from your iPhone if it is installed already for testing. Go to the Build menu in Xcode and Clean all Targets. Then recompile.

Check now to see if your HTML file actually sees your js file now.

Linda

Linda
A: 

The solution is a lot easier than that. I blogged about it here

It's a problem with xcode and can be easily solved, just follow my directions.

amok