Skip to content

Instantly share code, notes, and snippets.

@amster
Last active October 24, 2022 20:44
Show Gist options
  • Save amster/9160860 to your computer and use it in GitHub Desktop.
Save amster/9160860 to your computer and use it in GitHub Desktop.
Load a UIWebView in iOS that can also load local resources like images, CSS, and JavaScript
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="your_styles.css" type="text/css">
<script src="your_javascript.js"></script>
</head>
<body>
<h1>Big Title</h1>
<!-- Again, all bundle resources must have unique filenames -->
<img src="some_image.jpg" width="100%">
<!-- Example interaction -->
<button id="exampleButton" onclick="document.getElementById('debug').innerHTML='Was clicked';">Click?</button>
<p id="debug"></p>
</body>
</html>
// An example viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadWebView];
}
// The example loader
//
// Assumes you have an IBOutlet for the UIWebView defined: @property (strong, nonatomic) UIWebView *wv;
- (void)loadWebView {
// Remember that bundle resources do *not* have directories so all filenames must be unique.
NSBundle *mainBundle = [NSBundle mainBundle];
NSURL *homeIndexUrl = [mainBundle URLForResource:@"home_index" withExtension:@"html"];
// The magic is loading a request, *not* using loadHTMLString:baseURL:
NSURLRequest *urlReq = [NSURLRequest requestWithURL:homeIndexUrl];
[self.wv loadRequest:urlReq];
}
@WanChengCheng
Copy link

Great, this magic really works! thanks a lot 👍

@Remonell
Copy link

Could I also read a local json file for example via javascript like that? Thats not possible in Safari or Chrome right now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment