Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active December 13, 2015 19:39
Show Gist options
  • Save kristopherjohnson/4964560 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/4964560 to your computer and use it in GitHub Desktop.
UIWebView category method for loading HTML from the resource bundle. Content will be loaded such that the resource bundle directory is the base URL, so relative links (spreadsheets, images, etc.) work properly.
#import <UIKit/UIKit.h>
@interface UIWebView (XXXLoadHTMLResourceNamed)
// Load content from HTML resource file with specified name.
//
// Resource will be loaded using URL, and base URL will be the
// resource bundle directory, so relative paths will work properly.
- (void)loadHTMLResourceNamed:(NSString *)resourceName;
@end
#import "UIWebView+XXXLoadHTMLResourceNamed.h"
@implementation UIWebView (XXXLoadHTMLResourceNamed)
// Load content from HTML resource file with specified name.
//
// Resource will be loaded using URL, and base URL will be the
// resource bundle directory, so relative paths will work properly.
- (void)loadHTMLResourceNamed:(NSString *)resourceName {
NSBundle *bundle = [NSBundle mainBundle];
NSURL *htmlFileURL = [bundle URLForResource:resourceName
withExtension:@"html"];
NSError *error;
NSString *htmlContent = [NSString stringWithContentsOfURL:htmlFileURL
encoding:NSUTF8StringEncoding
error:&error];
if (error) {
NSLog(@"%s: Unable to load HTML: %@",
__PRETTY_FUNCTION__, [error localizedDescription]);
}
else {
NSURL *baseURL = [NSURL fileURLWithPath:[bundle resourcePath]
isDirectory:YES];
[self loadHTMLString:htmlContent baseURL:baseURL];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment