When loading URLs for UIWebView, I usually do it like this:
1. I get the path for my resource, then pass this to other functions.
1 |
NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"about" ofType:@"html"]; |
2. Create the NSURL using the html path.
1 |
NSURL *localHTMLURL = [NSURL URLWithString:htmlPath]; |
3. Create the NSURLRequest which will be passed to our UIWebView.
1 2 3 |
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; |
4. Load NSURLRequest to our UIWebView.
1 2 |
UIWebView *localWebView = [[UIWebView alloc] init]; [localWebView loadRequest:request]; |
Running this in the device will be okay. The HTML will be loaded successfully.
But running this in the iOS simulator will fail loading the HTML. This is because [NSURL URLWithString:]
must take in a string that conforms to RFC 2396.
When running in a device, the htmlPath
variable above will contain something like the following:
1 |
/var/mobile/Applications/AAAAA-1111-BBB222-333333-1234ABCD567/Sample.app/en.lproj/about.html |
The htmlPath
variable does not contain any spaces, which will make [NSURL URLWithString:]
return a non-nil object.
When running in the iOS Simulator, the htmlPath
variable above will contain something like the following:
1 |
/Users/myusername/Library/Application Support/iPhone Simulator/7.0/Applications/AAAAA-1111-BBB222-333333-1234ABCD567/Sample.app/en.lproj/about.html |
The path above contains spaces, which will make [NSURL URLWithString:]
return nil.
To address this problem, we will use another API to create the NSURL, once which is specifically for system paths, [NSURL fileURLWithPath:]
.
We will replace #2 with the following line:
1 |
NSURL *localHTMLURL = [NSURL fileURLWithPath:htmlPath]; |
Better yet, we will specify that the specified path is a file, and not a directory. This will save some i/o, according to Apple’s documentation in the NSURL header.
1 |
NSURL *localHTMLURL = [NSURL fileURLWithPath:htmlPath isDirectory:NO]; |
That’s it!
References:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html
You can avoid all those lines of code by simply calling:
NSURL *htmlURL = [[NSBundle mainBundle] URLForResource:@”yourFileName” withExtension:@”html”];
Thanks for the tip! I’ll try this API when I get the chance.