Programming Reference/Librarys
Question & Answer
Q&A is closed
This is an old revision of the document!
Sometimes you need or want to load a UIWebView displaying content provided with an app. If there is more then one site it might make sense to have an external .css or .js file for all your html content. Whatever, I was facing this problem currently and decided to provide my solution to you.
If you're following this example it is necessary that you are familiar with XCode and UIWebView-Basics.
First we will create the project. Open up XCode and click File→New→Project. Single View Application is the template we want for this purpose. Select it and click next. Now provide a name for your project. I named mine 'UIWebViewSample'.
In the ViewController.m and make your interface declaration at the top look like this:
@interface ViewController () <UIWebViewDelegate> @property(nonatomic, strong) IBOutlet UIWebView *webView; @property(nonatomic, assign) IBOutlet UIBarButtonItem *backBarButton; @end
Next we will add some code to load the webView and make the backBarButton usable.
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // ** FIX FOR iOS 7 ** if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0) { self.automaticallyAdjustsScrollViewInsets = NO; } // ** SET NAVIGATION ITEM DISABLED ** _backBarButton.enabled = NO; // ** DECORATE WEB-VIEW A BIT ** _webView.layer.borderWidth = 3.0f; _webView.layer.borderColor = [[UIColor grayColor]CGColor]; // ** LOAD WEB-VIEW ** [self loadWebView]; }
- (IBAction)navigationButtonAction:(id)sender { if ([sender isKindOfClass:[UIBarButtonItem class]]) { UIBarButtonItem *buttonItem = (UIBarButtonItem *)sender; switch (buttonItem.tag) { case 0: [self loadWebView]; _backBarButton.enabled = NO; break; default: break; } } }
- (void)loadWebView { // ** GET BUNDLE-PATH TO BUILD THE 'baseURL' ** NSString *bundlePath = [[NSBundle mainBundle] bundlePath]; NSURL *baseURL = [NSURL fileURLWithPath:bundlePath]; // ** GET PATH-STRING OF 'index.html' FILE ** NSString *filePath = [NSBundle pathForResource:@"index" ofType:@"html" inDirectory:bundlePath]; // ** GET HTML-STRING OF FILE ** NSString* htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; // ** START LOADING WEBVIEW WITH 'htmlString' AND 'baseURL' ** [_webView loadHTMLString:htmlString baseURL:baseURL]; }
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if (navigationType == UIWebViewNavigationTypeLinkClicked) { _backBarButton.enabled = YES; } return YES; }