In iOS UIWebView Tutorial, I have covered how to use UIWebView (WebView) in iOS and how to control it programmatically.
Topics covered in this article are
1) How to add UIWebView to a View
2) Load Request/Data in UIWebView
3) UIWebViewDelegate methods
4) Execute Javascript in UIWebView
5) Create UIWebView programmatically
1) How to add UIWebView to a View
Drag and drop UIWebView Widget from Object Library to storyboard.
Add an IBOutlet to view controller and link it to WebView as shown in the below image.
Viewcontroller.h looks like:
@interface ViewController : UIViewController { } @property (weak, nonatomic) IBOutlet UIWebView *webview; @end
2).Loading Request in Webview
To load a request you can use the below methods.
2.1) requestWithURL is used to load a URL in Webview
NSMutableURLRequest * request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]; [webview loadRequest:request];
2.2) loadHTMLString is used load HTML string in UIWebView
You can use the below code to load HTML string in webview
NSString * string = @"<html><body><h1>Hayageek</h1>How to <a href=\"/add-custom-fonts-ios/\">Add Custom Font</a>"; [webview loadHTMLString:string baseURL:[NSURL URLWithString:@"https://hayageek.com"]];
2.3) loadData method is used to Load NSData in webview. Documents like .doc,.pdf,.xls,.txt,…etc are opened with UIWebview.
NSString * path =[[NSBundle mainBundle] pathForResource:@"Resume" ofType:@"doc"]; NSData *data =[[NSFileManager defaultManager] contentsAtPath:path]; [webview loadData:data MIMEType:@"application/msword" textEncodingName:@"UTF-8"baseURL:nil];
To get the list of MIME types:http://webdesign.about.com/od/multimedia/a/mime-types-by-content-type.htm
3).UIWebViewDelegate methods.
In order to get UIWebViewDelegate callbacks, you need to add UIWebViewDelegate protocol to your class and set the webview delegate class.
ViewController.h Source:
@interface ViewController : UIViewController<UIWebViewDelegate> { } @property (weak, nonatomic) IBOutlet UIWebView *webview; @end
ViewController.m Source:
@implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [webview setDelegate:self]; } @end
UIWebViewDelegate has the following delegate methods.
3.1) webView:shouldStartLoadWithRequest:navigationType: method is called before loading a frame. If the method returns YES, request is loaded. Otherwise NO.
Using this method, requests can be filtered.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSLog(@"Loading URL :%@",request.URL.absoluteString); //return FALSE; //to stop loading return YES; }
Filtering Clicks, Form Submission,Ads:
//To avoid link clicking. if(navigationType ==UIWebViewNavigationTypeLinkClicked) return NO; //To avoid form submission. if(navigationType ==UIWebViewNavigationTypeFormSubmitted) return NO; //To avoid loading all the google ads. if([request.URL.absoluteString rangeOfString:@"googleads"].location != NSNotFound) return NO;
3.2)webViewDidStartLoad method is called when a frame starts loading.
- (void)webViewDidStartLoad:(UIWebView *)webView { }
3.3)webViewDidFinishLoad method is called when a frame finishes loading.
- (void)webViewDidFinishLoad:(UIWebView *)webView { }
3.4) webView:didFailLoadWithError: method is called if frame loading is failed.
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { NSLog(@"Failed to load with error :%@",[error debugDescription]); }
4) Execute JavaScript in UIWebview.
You can execute javascript programmatically in WebView using the method stringByEvaluatingJavaScriptFromString.
Examples:
//Show Cookie as alert in WebView [webview stringByEvaluatingJavaScriptFromString:@"alert(document.cookie)"]; //Get Cookie NSString * cookie=[webview stringByEvaluatingJavaScriptFromString:@"document.cookie"]; NSLog(@"cookie =%@",cookie); //Get sum of 2+3 NSString * result1 =[webview stringByEvaluatingJavaScriptFromString:@"2+3"]; NSLog(@"2+3:%ld",(long)[result1 integerValue]); //Redirect the current page in WebView [webview stringByEvaluatingJavaScriptFromString:@"location.href=\"http://apple.com\""];
4).How to add a UIWebview to View Programmatically
UIWebview is added to a View programmatically using the below code.
- (void)viewDidLoad { [super viewDidLoad]; //set desired width and height UIWebView *myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 100, 300, 300)]; [myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]]; [self.view addSubview:myWebView]; }
Reference: Apple Documentation