Showing posts with label UIWebView example. Show all posts
Showing posts with label UIWebView example. Show all posts

Monday, June 3, 2013

UIWebView UIWebViewNavigationTypeOther example in Objective C (iOS).


UIWebView UIWebViewNavigationTypeOther

UIWebViewNavigationType
Constant indicating the user’s action.

enum {
UIWebViewNavigationTypeLinkClicked,
UIWebViewNavigationTypeFormSubmitted,
UIWebViewNavigationTypeBackForward,
UIWebViewNavigationTypeReload,
UIWebViewNavigationTypeFormResubmitted,
UIWebViewNavigationTypeOther
};
typedef NSUInteger UIWebViewNavigationType;

Constants
UIWebViewNavigationTypeLinkClicked
User tapped a link.
UIWebViewNavigationTypeFormSubmitted
User submitted a form.
UIWebViewNavigationTypeBackForward
User tapped the back or forward button.
UIWebViewNavigationTypeReload
User tapped the reload button.
UIWebViewNavigationTypeFormResubmitted
User resubmitted a form.
UIWebViewNavigationTypeOther
Some other action occurred.

UIWebView UIWebViewNavigationTypeOther example.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
DrillDownWebExampleAppDelegate *appDelegate =
(DrillDownWebExampleAppDelegate *)[[UIApplication sharedApplication] delegate];

if(navigationType == UIWebViewNavigationTypeOther)
{
    NSURL *url2 = [request URL];
    NSString *URLStr = [url2 absoluteString];

    RootViewController* viewController = [[RootViewController alloc] init];
    NSString *holder = [self getQueryStringInner:URLStr];
    [self getQueryString:URLStr];
    if([holder length] != 0 )
    {
        appDelegate.title =@"Title";
        appDelegate.query = queryString;
        [self.navigationController pushViewController:viewController animated:YES];
        [viewController release];
        return NO;
    }


}
return YES;
}

Example of [UIWebView UIWebViewNavigationTypeOther].
- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
  if (navigationType != UIWebViewNavigationTypeOther) {
    self.outStandingLoads = 0;
  }
  return YES;
}

End of UIWebView UIWebViewNavigationTypeOther example article.

UIWebView UIWebViewNavigationTypeReload example in Objective C (iOS).


UIWebView UIWebViewNavigationTypeReload

UIWebViewNavigationType
Constant indicating the user’s action.

enum {
UIWebViewNavigationTypeLinkClicked,
UIWebViewNavigationTypeFormSubmitted,
UIWebViewNavigationTypeBackForward,
UIWebViewNavigationTypeReload,
UIWebViewNavigationTypeFormResubmitted,
UIWebViewNavigationTypeOther
};
typedef NSUInteger UIWebViewNavigationType;

Constants
UIWebViewNavigationTypeLinkClicked
User tapped a link.
UIWebViewNavigationTypeFormSubmitted
User submitted a form.
UIWebViewNavigationTypeBackForward
User tapped the back or forward button.
UIWebViewNavigationTypeReload
User tapped the reload button.
UIWebViewNavigationTypeFormResubmitted
User resubmitted a form.
UIWebViewNavigationTypeOther
Some other action occurred.

UIWebView UIWebViewNavigationTypeReload example.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"shouldStartLoadWithRequest");

    if ( navigationType == UIWebViewNavigationTypeLinkClicked ){
        NSLog(@"UIWebViewNavigationTypeLinkClicked");

        return YES;
    }
    if (navigationType ==UIWebViewNavigationTypeFormSubmitted ) {
        NSLog(@"UIWebViewNavigationTypeFormSubmitted");
        return YES;
    }
    if (navigationType ==UIWebViewNavigationTypeBackForward) {
        NSLog(@"UIWebViewNavigationTypeBackForward");
        return YES;
    }
    if (navigationType ==UIWebViewNavigationTypeFormResubmitted) {
        NSLog(@"UIWebViewNavigationTypeFormResubmitted");
        return YES;
    }
    if (navigationType ==UIWebViewNavigationTypeReload) {
        NSLog(@"UIWebViewNavigationTypeReload");
        return YES;
    }


    return YES;
}

Example of [UIWebView UIWebViewNavigationTypeReload].
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{      //If you want to block ANY navigation
    return NO;

       //If you want to block refreshes but allow other navigation
     if (navigationType == UIWebViewNavigationTypeReload) return NO;
{

UIWebView UIWebViewNavigationTypeReload example.
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request
navigationType:(UIWebViewNavigationType)navigationType
{
if (navigationType == UIWebViewNavigationTypeLinkClicked ||
navigationType == UIWebViewNavigationTypeFormSubmitted ||
navigationType == UIWebViewNavigationTypeReload  ||
navigationType == UIWebViewNavigationTypeFormResubmitted)
{
         .....
        }

End of UIWebView UIWebViewNavigationTypeReload example article.

UIWebView UIWebViewNavigationTypeBackForward example in Objective C (iOS).


UIWebView UIWebViewNavigationTypeBackForward

UIWebViewNavigationType
Constant indicating the user’s action.

enum {
UIWebViewNavigationTypeLinkClicked,
UIWebViewNavigationTypeFormSubmitted,
UIWebViewNavigationTypeBackForward,
UIWebViewNavigationTypeReload,
UIWebViewNavigationTypeFormResubmitted,
UIWebViewNavigationTypeOther
};
typedef NSUInteger UIWebViewNavigationType;

Constants
UIWebViewNavigationTypeLinkClicked
User tapped a link.
UIWebViewNavigationTypeFormSubmitted
User submitted a form.
UIWebViewNavigationTypeBackForward
User tapped the back or forward button.
UIWebViewNavigationTypeReload
User tapped the reload button.
UIWebViewNavigationTypeFormResubmitted
User resubmitted a form.
UIWebViewNavigationTypeOther
Some other action occurred.

UIWebView UIWebViewNavigationTypeBackForward example.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"shouldStartLoadWithRequest");

    if ( navigationType == UIWebViewNavigationTypeLinkClicked ){
        NSLog(@"UIWebViewNavigationTypeLinkClicked");

        return YES;
    }
    if (navigationType ==UIWebViewNavigationTypeFormSubmitted ) {
        NSLog(@"UIWebViewNavigationTypeFormSubmitted");
        return YES;
    }
    if (navigationType ==UIWebViewNavigationTypeBackForward) {
        NSLog(@"UIWebViewNavigationTypeBackForward");
        return YES;
    }
    if (navigationType ==UIWebViewNavigationTypeFormResubmitted) {
        NSLog(@"UIWebViewNavigationTypeFormResubmitted");
        return YES;
    }
    if (navigationType ==UIWebViewNavigationTypeReload) {
        NSLog(@"UIWebViewNavigationTypeReload");
        return YES;
    }


    return YES;
}

Example of [UIWebView UIWebViewNavigationTypeBackForward].
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
   
    if  (navigationType == UIWebViewNavigationTypeLinkClicked || navigationType == UIWebViewNavigationTypeBackForward)
    {
        NSURL *loadURL = [[request URL] retain];
        [[UIApplication sharedApplication] openURL:loadURL]; // Ну или что вы хотите делать с этой ссылкой
        [loadURL release];
        return NO;
    }
    return YES;
}

UIWebView UIWebViewNavigationTypeBackForward example.
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request
navigationType:(UIWebViewNavigationType)navigationType
{
if (navigationType == UIWebViewNavigationTypeLinkClicked ||
navigationType == UIWebViewNavigationTypeFormSubmitted ||
navigationType == UIWebViewNavigationTypeBackForward ||
navigationType == UIWebViewNavigationTypeFormResubmitted)
{
         .....
        }

End of UIWebView UIWebViewNavigationTypeBackForward example article.

UIWebView UIWebViewNavigationTypeLinkClicked example in Objective C (iOS).


UIWebView UIWebViewNavigationTypeLinkClicked

UIWebViewNavigationType
Constant indicating the user’s action.

enum {
UIWebViewNavigationTypeLinkClicked,
UIWebViewNavigationTypeFormSubmitted,
UIWebViewNavigationTypeBackForward,
UIWebViewNavigationTypeReload,
UIWebViewNavigationTypeFormResubmitted,
UIWebViewNavigationTypeOther
};
typedef NSUInteger UIWebViewNavigationType;

Constants
UIWebViewNavigationTypeLinkClicked
User tapped a link.
UIWebViewNavigationTypeFormSubmitted
User submitted a form.
UIWebViewNavigationTypeBackForward
User tapped the back or forward button.
UIWebViewNavigationTypeReload
User tapped the reload button.
UIWebViewNavigationTypeFormResubmitted
User resubmitted a form.
UIWebViewNavigationTypeOther
Some other action occurred.

UIWebView UIWebViewNavigationTypeLinkClicked example.
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
    NSURL *requestURL =[ [ request URL ] retain ];
    if ( ( [ [ requestURL scheme ] isEqualToString: @"http" ] || [ [ requestURL scheme ] isEqualToString: @"https" ] || [ [ requestURL scheme ] isEqualToString: @"mailto" ])
        && ( navigationType == UIWebViewNavigationTypeLinkClicked ) ) {
        return ![ [ UIApplication sharedApplication ] openURL: [ requestURL autorelease ] ];
    }
    [ requestURL release ];
    return YES;
}

Example of [UIWebView UIWebViewNavigationTypeLinkClicked].
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        [[UIApplication sharedApplication] openURL:request.URL];
        return false;
    }
    return true;
}

UIWebView UIWebViewNavigationTypeLinkClicked example.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    // Check if this was a click event and then some other criteria for determining if you want to launch Safari.
    if (navigationType == UIWebViewNavigationTypeLinkClicked && [Some other criteria]) {
        [[UIApplication sharedApplication] openURL:request.URL];

        // Return false to indicate to the UIWebView to not navigate to the linked target
        return false;
    }

    // Return true so that the UIWebView loads the link target
    return true;
}

End of UIWebView UIWebViewNavigationTypeLinkClicked example article.

UIWebView stopLoading example in Objective C (iOS).


UIWebView stopLoading

Stops the loading of any web content managed by the receiver.

- (void)stopLoading

Discussion of [UIWebView stopLoading]
Stops any content in the process of being loaded by the main frame or any of its children frames. Does nothing if no content is being loaded.

UIWebView stopLoading example.
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [webView  stopLoading ];
    [webView reload];
}
or

NSURL *theURL = [NSURL URLWithString:@"http://www.OurLovingMother.org/Mobile.aspx"];
    [webView loadRequest:[NSURLRequest requestWithURL:theURL]];
}

Example of [UIWebView stopLoading].
TRy with, First call stopLoading then reload on your UIWebView instance.

[myWebView  stopLoading ];
[myWebView  reload];

UIWebView stopLoading example.
[webView loadRequest: [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.facebook.com"]]];
[webView  stopLoading ];
[webView reload];

End of UIWebView stopLoading example article.

UIWebView reload example in Objective C (iOS).


UIWebView reload

Reloads the current page.

- (void)reload

UIWebView reload example.
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [webView  stopLoading ];
    [webView reload];
}
or

NSURL *theURL = [NSURL URLWithString:@"http://www.OurLovingMother.org/Mobile.aspx"];
    [webView loadRequest:[NSURLRequest requestWithURL:theURL]];
}

Example of [UIWebView reload].
TRy with, First call stopLoading then reload on your UIWebView instance.

[myWebView  stopLoading ];
[myWebView  reload];

UIWebView reload example.
[webView loadRequest: [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.facebook.com"]]];
[webView  stopLoading ];
[webView reload];

End of UIWebView reload example article.

UIWebView loadRequest example in Objective C (iOS).


UIWebView loadRequest

Connects to a given URL by initiating an asynchronous client request.

- (void)loadRequest:(NSURLRequest *)request

Parameters of [UIWebView loadRequest]
request
A URL request identifying the location of the content to load.

Discussion of [UIWebView loadRequest]
To stop this load, use the stopLoading method. To see whether the receiver is done loading the content, use the loading property.

UIWebView loadRequest example.
- (void)viewDidLoad {
  [super viewDidLoad];
webView.delegate = self;
  NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
  NSURLRequest *request = [NSURLRequest requestWithURL:url];
  [webView setScalesPageToFit:YES];        
  [self.webView loadRequest:request];              
}

Example of [UIWebView loadRequest].
NSString *urlAddress = @"http://www.google.com";

    //Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];

    //URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

    //Load the request in the UIWebView.
[webView loadRequest:requestObj];

UIWebView loadRequest example.
[activityIndicator startAnimating];

NSURL *url = [NSURL URLWithString:urlWeb];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[vue loadRequest:request];
vue.scalesPageToFit = YES;
And here is the protocol methods

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [activityIndicator stopAnimating];
}

End of UIWebView loadRequest example article.

UIWebView loadHTMLString baseURL example in Objective C (iOS).


UIWebView loadHTMLString baseURL

Sets the main page content and base URL.

- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL

Parameters of [UIWebView loadHTMLString baseURL]
string
The content for the main page.
baseURL
The base URL for the content.

UIWebView loadHTMLString baseURL example.
- (id)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code.
        CGRect oFrame = frame;
        CGPoint oPositionCoords = CGPointMake(0, 0);
        oFrame.origin = oPositionCoords;

        m_oDataPresentView = [[UIWebView alloc] initWithFrame:oFrame];
        [m_oDataPresentView loadHTMLString:@"<html><body style=\"background-color: #000000; color: #FFFFFF; font-family: Helvetica; font-size: 10pt; width: 300px; word-wrap: break-word;\"></body></html>" baseURL:nil];
        m_oDataPresentView.delegate = self;

        [self addSubview:m_oDataPresentView];
    }
    return self;
}

Example of [UIWebView loadHTMLString baseURL].
- (void) showWebView:(NSString *)htmlText{
    [webView setHidden:FALSE];
    [txtContent setHidden:TRUE];

    NSString * htmlString = [NSString stringWithFormat:@"<html><head><style type='text/css'>body {background-color:transparent; } p { color:white; font-family:Helvetica; font-size:14px; } a { color:white; }</style></head><body><p>%@</p></body></html>", htmlText];
    webView.delegate = self;

    NSLog(@"htmlstring  %@",htmlString);
   [webView loadHTMLString:htmlString baseURL:nil];
}
Under iOS5 I found that sometimes a UIWebView would not load its content if

<meta charset="utf-8"></meta>
(or other equivalent charset specification) was not present in the HTML.


UIWebView loadHTMLString baseURL example.
- (void)embedYouTube:(NSString*)urls frame:(CGRect)frame {

    urls=[urls stringByAppendingString:@"&autoplay=1"];
    NSString *htmlString =[NSString stringWithFormat: @"<html><head> <meta name = \"viewport\" content = \"initial-scale = 1.0, user-scalable = no, width = 212\"/></head> <body style=\"background:#F00;margin-top:0px;margin-left:0px\"><div><object width=\"212\" height=\"212\"><param name=\"movie\" value=\"%@\">",urls];

    NSString *htm2=[NSString stringWithFormat:@"</param><param name=\"wmode\" value=\"transparent\"></param>    <embed src=\"%@\"type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"212\" height=\"212\"></embed>    </object></div></body></html>",urls];
//    NSString* embedHTML = @"<html><head> </head><body style=\"margin:0\"> <iframe title=\"YouTube video player\" class=\"youtube-player\" type=\"text/html\" width=\"%d\" height=\"%d\" src=\"%@\" frameborder=\"0\" allowFullScreen></iframe> </body></html>"; 

    NSString* html = [NSString stringWithFormat:@"%@%@",htmlString,htm2];
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];

    if(version<5.0)
    {

        NSRange r=[urls rangeOfString:@"v="];
        NSRange ran=NSMakeRange(r.location+2, [urls length]-r.location-2);
        NSString *vid=[urls substringWithRange:ran];
    html=[NSString stringWithFormat:@"<embed id=\"yt\" src=\"http://www.youtube.com/watch?v=%@&fs=0\" type=\"application/x-shockwave-flash\" width=\"300\" height=\"300\"></embed>", vid];
    }
    //NSLog(html);
    if(webView == nil) { 
        webView = [[UIWebView alloc] initWithFrame:frame]; 
        [self.view addSubview:webView]; 
        [webView setDelegate:self];
    } 
    [webView loadHTMLString:html baseURL:nil]; 
}

End of UIWebView loadHTMLString baseURL example article.

UIWebView loadHTMLString example in Objective C (iOS).


UIWebView loadHTMLString

Sets the main page content and base URL.

- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL

Parameters of [UIWebView loadHTMLString]
string
The content for the main page.
baseURL
The base URL for the content.

UIWebView loadHTMLString example.
- (id)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code.
        CGRect oFrame = frame;
        CGPoint oPositionCoords = CGPointMake(0, 0);
        oFrame.origin = oPositionCoords;

        m_oDataPresentView = [[UIWebView alloc] initWithFrame:oFrame];
        [m_oDataPresentView loadHTMLString:@"<html><body style=\"background-color: #000000; color: #FFFFFF; font-family: Helvetica; font-size: 10pt; width: 300px; word-wrap: break-word;\"></body></html>" baseURL:nil];
        m_oDataPresentView.delegate = self;

        [self addSubview:m_oDataPresentView];
    }
    return self;
}

Example of [UIWebView loadHTMLString].
- (void) showWebView:(NSString *)htmlText{
    [webView setHidden:FALSE];
    [txtContent setHidden:TRUE];

    NSString * htmlString = [NSString stringWithFormat:@"<html><head><style type='text/css'>body {background-color:transparent; } p { color:white; font-family:Helvetica; font-size:14px; } a { color:white; }</style></head><body><p>%@</p></body></html>", htmlText];
    webView.delegate = self;

    NSLog(@"htmlstring  %@",htmlString);
   [webView loadHTMLString:htmlString baseURL:nil];
}
Under iOS5 I found that sometimes a UIWebView would not load its content if

<meta charset="utf-8"></meta>
(or other equivalent charset specification) was not present in the HTML.


UIWebView loadHTMLString example.
- (void)embedYouTube:(NSString*)urls frame:(CGRect)frame {

    urls=[urls stringByAppendingString:@"&autoplay=1"];
    NSString *htmlString =[NSString stringWithFormat: @"<html><head> <meta name = \"viewport\" content = \"initial-scale = 1.0, user-scalable = no, width = 212\"/></head> <body style=\"background:#F00;margin-top:0px;margin-left:0px\"><div><object width=\"212\" height=\"212\"><param name=\"movie\" value=\"%@\">",urls];

    NSString *htm2=[NSString stringWithFormat:@"</param><param name=\"wmode\" value=\"transparent\"></param>    <embed src=\"%@\"type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"212\" height=\"212\"></embed>    </object></div></body></html>",urls];
//    NSString* embedHTML = @"<html><head> </head><body style=\"margin:0\"> <iframe title=\"YouTube video player\" class=\"youtube-player\" type=\"text/html\" width=\"%d\" height=\"%d\" src=\"%@\" frameborder=\"0\" allowFullScreen></iframe> </body></html>"; 

    NSString* html = [NSString stringWithFormat:@"%@%@",htmlString,htm2];
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];

    if(version<5.0)
    {

        NSRange r=[urls rangeOfString:@"v="];
        NSRange ran=NSMakeRange(r.location+2, [urls length]-r.location-2);
        NSString *vid=[urls substringWithRange:ran];
    html=[NSString stringWithFormat:@"<embed id=\"yt\" src=\"http://www.youtube.com/watch?v=%@&fs=0\" type=\"application/x-shockwave-flash\" width=\"300\" height=\"300\"></embed>", vid];
    }
    //NSLog(html);
    if(webView == nil) { 
        webView = [[UIWebView alloc] initWithFrame:frame]; 
        [self.view addSubview:webView]; 
        [webView setDelegate:self];
    } 
    [webView loadHTMLString:html baseURL:nil]; 
}

End of UIWebView loadHTMLString example article.

UIWebView loadData MIMEType textEncodingName baseURL example in Objective C (iOS).


UIWebView loadData MIMEType textEncodingName baseURL

Sets the main page contents, MIME type, content encoding, and base URL.

- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL

Parameters of [UIWebView loadData MIMEType textEncodingName baseURL]
data
The content for the main page.
MIMEType
The MIME type of the content.
encodingName
The IANA encoding name as in utf-8 or utf-16.
baseURL
The base URL for the content.

UIWebView loadData MIMEType textEncodingName baseURL example.
- (void)viewDidLoad
{

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html" inDirectory:@"html_files"];

NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
webView = [UIWebView alloc] init];
[webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];

[super viewDidLoad];
}

Example of [UIWebView loadData MIMEType textEncodingName baseURL].
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
        webdata = [[NSMutableData alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [webdata appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    [mWebView loadData:webdata MIMEType: @"text/html" textEncodingName: @"UTF-8" baseURL:nil];
}

UIWebView loadData MIMEType textEncodingName baseURL example.

CGRect frame = CGRectMake(50,50,0,0);
frame.size = [UIImage imageNamed:@"anim.gif"].size;
//
NSData *gif = [NSData dataWithContentsOfFile:
    [[NSBundle mainBundle] pathForResource:@"anim" ofType:@"gif"]];
// view
UIWebView *view = [[UIWebView alloc] initWithFrame:frame];
[view loadData:gif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];

End of UIWebView loadData MIMEType textEncodingName baseURL example article.

UIWebView loadData example in Objective C (iOS).


UIWebView loadData

Sets the main page contents, MIME type, content encoding, and base URL.

- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL

Parameters of [UIWebView loadData]
data
The content for the main page.
MIMEType
The MIME type of the content.
encodingName
The IANA encoding name as in utf-8 or utf-16.
baseURL
The base URL for the content.

UIWebView loadData example.
- (void)viewDidLoad
{

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html" inDirectory:@"html_files"];

NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
webView = [UIWebView alloc] init];
[webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];

[super viewDidLoad];
}

Example of [UIWebView loadData].
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
        webdata = [[NSMutableData alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [webdata appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    [mWebView loadData:webdata MIMEType: @"text/html" textEncodingName: @"UTF-8" baseURL:nil];
}

UIWebView loadData example.

CGRect frame = CGRectMake(50,50,0,0);
frame.size = [UIImage imageNamed:@"anim.gif"].size;
//
NSData *gif = [NSData dataWithContentsOfFile:
    [[NSBundle mainBundle] pathForResource:@"anim" ofType:@"gif"]];
// view
UIWebView *view = [[UIWebView alloc] initWithFrame:frame];
[view loadData:gif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];

End of UIWebView loadData example article.

UIWebView goForward example in Objective C (iOS).


UIWebView goForward

Loads the next location in the back-forward list.

- (void)goForward

UIWebView goForward example.
-(IBAction) back
{

   [myWebView goBack];
}
-(IBAction) forward
{

   [myWebView goForward];
}

Example of [UIWebView goForward].
- (void)webViewDidStartLoad:(UIWebView*)webView
{
    [_backButton setEnabled:(webView.canGoBack)];
    [_forwardButton setEnabled:(webView.canGoForward)];
}

UIWebView goForward example.
- (IBAction)goBack {
    [signUpWebView goBack];
}

- (IBAction)goForward {
    [signUpWebView goForward];
}

- (void)webViewDidStartLoad:(UIWebView *)mwebView {
    backButton.enabled = (webView.canGoBack);
    forwardButton.enabled = (webView.canGoForward);
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    backButton.enabled = (webView.canGoBack);
    forwardButton.enabled = (webView.canGoForward);
}

End of UIWebView goForward example article.

UIWebView goBack example in Objective C (iOS).


UIWebView goBack

Loads the previous location in the back-forward list.

- (void)goBack

UIWebView goBack example.
Sample code:

if ([webView canGoBack]) {
    [webView goBack];
}

Example of [UIWebView goBack].
NSString *urlAddress = @"http://www.stackoverflow.com";

 NSURL *url = [NSURL URLWithString:urlAddress];

 NSURLRequest *requestObj = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];

 [self.webview loadRequest:requestObj];
and then try your back navigation:

 [self.webview goBack]; 

End of UIWebView goBack example article.

UIWebView suppressesIncrementalRendering example in Objective C (iOS).


UIWebView suppressesIncrementalRendering

A Boolean value indicating whether the web view suppresses content rendering until it is fully loaded into memory.

@property(nonatomic) BOOL suppressesIncrementalRendering

Discussion of [UIWebView suppressesIncrementalRendering]
When set to YES, the web view does not attempt to render incoming content as it arrives. Instead, the view’s current contents remain in place until all of the new content has been received, at which point the new content is rendered. This property does not affect the rendering of content retrieved after a frame finishes loading.

The value of this property is NO by default.

UIWebView suppressesIncrementalRendering example.
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.frame];
NSString *urlAddress = @"https://mysite.com/";

NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
[webView setSuppressesIncrementalRendering:YES];
[self.view addSubview:webView];
[super viewDidLoad];

End of UIWebView suppressesIncrementalRendering example article.

UIWebView scrollView example in Objective C (iOS).


UIWebView scrollView

The scroll view associated with the web view. (read-only)

@property(nonatomic, readonly, retain) UIScrollView *scrollView

Discussion of [UIWebView scrollView]
Your application can access the scroll view if it wants to customize the scrolling behavior of the web view.

UIWebView scrollView example.
- (UIScrollView *)getScrollViewFromWebView: (UIWebView*) webView {
    UIScrollView *scrollView = nil;

    NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
    if ([currSysVer compare:@"5.0" options:NSNumericSearch] != NSOrderedAscending) {
        return webView.scrollView;
    }
    else {
        for (UIView *subview in [webView subviews]) {
            if ([subview isKindOfClass:[UIScrollView class]]) {
                scrollView = (UIScrollView *)subview;
            }
        }

        if (scrollView == nil) {
            NSLog(@"Couldn’t get default scrollview!");
        }
    }
    return scrollView;
}

Example of [UIWebView scrollView].
The issue isn't the setScrollEnabled: call. It's actually that the scrollView of the UIWebView wasn't exposed until iOS 5 (which is why it fails on anything else). See the UIWebView documentation for further information.

In previous versions of iOS, you had to resort to iterating through the subviews of your UIWebView to find a UIScrollView.
UIScrollView* scrollView = nil;
for (UIView* subview in [webView subviews]) {
   if ([subview isKindOfClass:[UIScrollView class]]) { 
      scrollView = (UIScrollView*)subview;
      scrollView.delegate = ;
      break;
   }
}

UIWebView scrollView example.
static int kObservingContentSizeChangesContext;

- (void)startObservingContentSizeChangesInWebView:(UIWebView *)webView {
    [webView.scrollView addObserver:self forKeyPath:@"contentSize" options:0 context:&kObservingContentSizeChangesContext];
}

- (void)stopObservingContentSizeChangesInWebView:(UIWebView *)webView {
    [webView.scrollView removeObserver:self forKeyPath:@"contentSize" context:&kObservingContentSizeChangesContext];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == &kObservingContentSizeChangesContext) {
        UIScrollView *scrollView = object;
        NSLog(@"%@ contentSize changed to %@", scrollView, NSStringFromCGSize(scrollView.contentSize));
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

End of UIWebView scrollView example article.

UIWebView scalesPageToFit example in Objective C (iOS).


UIWebView scalesPageToFit

A Boolean value determining whether the webpage scales to fit the view and the user can change the scale.

@property(nonatomic) BOOL scalesPageToFit

Discussion of [UIWebView scalesPageToFit]
If YES, the webpage is scaled to fit and the user can zoom in and zoom out. If NO, user zooming is disabled. The default value is NO.

UIWebView scalesPageToFit example.
- (void)viewDidLoad {
    [super viewDidLoad];
    webView = [[UIWebView alloc] init];
    webView.scalesPageToFit = YES;
    webView.backgroundColor = [UIColor blackColor];

    self.view.alpha = 1;
    self.view.backgroundColor = [UIColor whiteColor];
}

Example of [UIWebView scalesPageToFit].
view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200.0f, 400.0f)];
webViewT = [[UIWebView alloc] initWithFrame:view.bounds];
webViewT.delegate = self;
webViewT.scalesPageToFit = YES;
NSURL* url = [NSURL URLWithString:@"http://www.google.com/"];
[webViewT loadRequest:[NSURLRequest requestWithURL:url]];

In Some of cases this types of problem Generated. At that time java script use for control of Zoom of UIWebView, use following code.

NSString *jsCommand = [NSString stringWithFormat:@"document.body.style.zoom = 1.5;"];
[webLookupView stringByEvaluatingJavaScriptFromString:jsCommand];

UIWebView scalesPageToFit example.
In my experience, you need to set scalesPageToFit before the UIWebView loads. This means setting before viewDidLoad etc. What I do is set it in "shouldStartLoadWithRequest"

- (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //make sure that the page scales when it is loaded :-)
    theWebView.scalesPageToFit = YES;
    return YES;
}

End of UIWebView scalesPageToFit example article.

UIWebView mediaPlaybackRequiresUserAction example in Objective C (iOS).


UIWebView mediaPlaybackRequiresUserAction

A Boolean value that determines whether HTML5 videos can play automatically or require the user to start playing them.

@property(nonatomic) BOOL mediaPlaybackRequiresUserAction

Discussion of [UIWebView mediaPlaybackRequiresUserAction]
The default value on both iPad and iPhone is YES.

UIWebView mediaPlaybackRequiresUserAction example.
     NSString *html = [NSString stringWithFormat:embedHTML, webView.frame.size.width, webView.frame.size.height];
     [webView loadHTMLString:html baseURL:nil];
     webView.allowsInlineMediaPlayback = YES;
     webView.mediaPlaybackRequiresUserAction = NO;

     webView.transform = CGAffineTransformMakeRotation(3.14/2);

     [moviePlayerWindow addSubview:webView];

Example of [UIWebView mediaPlaybackRequiresUserAction].
- (void)viewDidLoad
{
    [super viewDidLoad];

    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 150)];
    [webView setMediaPlaybackRequiresUserAction:NO];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"YT_Player" ofType:@"html"] isDirectory:NO]]];
    [self.view addSubview:webView];
}

UIWebView mediaPlaybackRequiresUserAction example.
@implementation YouTubeWebView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self == nil) return nil;

    self.mediaPlaybackRequiresUserAction = NO;
    self.delegate = self;
    self.alpha = 0;

    return self;
}

- (void)loadVideo:(NSString *)videoId
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"youtube" ofType:@"html"];
    //    if (filePath == nil)

    NSError *error;
    NSString *string = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
    // TODO: error check

    string = [NSString stringWithFormat:string, videoId];

    NSData *htmlData = [string dataUsingEncoding:NSUTF8StringEncoding];
    //    if (htmlData == nil)

    NSString *documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *targetPath = [documentsDirectoryPath stringByAppendingPathComponent:@"youtube.html"];
    [htmlData writeToFile:targetPath atomically:YES];

    [self loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:targetPath]]];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([[[request URL] scheme] isEqualToString:@"callback"]) {
        [self removeFromSuperview];

        NSString *documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *targetPath = [documentsDirectoryPath stringByAppendingPathComponent:@"youtube.html"];
        NSError *error;
        [[NSFileManager defaultManager] removeItemAtPath:targetPath error:&error];
//        TODO: error check
    }

    return YES;
}

End of UIWebView mediaPlaybackRequiresUserAction example article.

UIWebView mediaPlaybackAllowsAirPlay example in Objective C (iOS).


UIWebView mediaPlaybackAllowsAirPlay

A Boolean value that determines whether Air Play is allowed from this view.

@property(nonatomic) BOOL mediaPlaybackAllowsAirPlay

Discussion of [UIWebView mediaPlaybackAllowsAirPlay]
The default value on both iPad and iPhone is YES.

UIWebView mediaPlaybackAllowsAirPlay example.
NSString *urlString = @"http://medialog.roamrlog.com/video.html";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:url];

_webView = [[UIWebView alloc] initWithFrame:CGRectMake(50, 20, 280, 200)];

_webView.delegate = self;

_webView.allowsInlineMediaPlayback = YES;
_webView.mediaPlaybackAllowsAirPlay = NO;

[_webView loadRequest:urlRequest];

End of UIWebView mediaPlaybackAllowsAirPlay example article.

UIWebView keyboardDisplayRequiresUserAction example in Objective C (iOS).


UIWebView keyboardDisplayRequiresUserAction

A Boolean value indicating whether web content can programmatically display the keyboard.

@property (nonatomic) BOOL keyboardDisplayRequiresUserAction

Discussion of [UIWebView keyboardDisplayRequiresUserAction]
When this property is set to YES, the user must explicitly tap the elements in the web view to display the keyboard (or other relevant input view) for that element. When set to NO, a focus event on an element causes the input view to be displayed and associated with that element automatically.

The default value for this property is YES.

UIWebView keyboardDisplayRequiresUserAction example.
Prior to iOS 6 this wasn't possible, but thankfully they've changed that. You can't do it in general for a website, but if you are embedding a UIWebView in your application you can do it now:

UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
webView.keyboardDisplayRequiresUserAction = NO;

Example of [UIWebView keyboardDisplayRequiresUserAction].
Prior to iOS 6, Apple only allowed the keyboard to be brought up following a user interaction. In iOS 6 they've introduced the following property for UIWebView which you merely need to set to NO.

    "yourWebView".keyboardDisplayRequiresUserAction = NO;
Apple sets this by default to "Yes". Now you can call focus() in your JS and the keyboard will appear.


End of UIWebView keyboardDisplayRequiresUserAction example article.

UIWebView dataDetectorTypes example in Objective C (iOS).


UIWebView dataDetectorTypes

The types of data converted to clickable URLs in the web view’s content.

@property(nonatomic) UIDataDetectorTypes dataDetectorTypes

Discussion of [UIWebView dataDetectorTypes]
You can use this property to specify the types of data (phone numbers, http links, email address, and so on) that should be automatically converted to clickable URLs in the web view. When clicked, the web view opens the application responsible for handling the URL type and passes it the URL.

UIWebView dataDetectorTypes example.
webview = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,320,460)];
webview.opaque = NO;
webview.backgroundColor = [UIColor clearColor];
webview.userInteractionEnabled = YES;
webview.dataDetectorTypes = UIDataDetectorTypeAll;

Example of [UIWebView dataDetectorTypes].
// ...

- (void)webViewDidStartLoad:(UIWebView *)theWebView
{
    theWebView.dataDetectorTypes = UIDataDetectorTypeAll ^ UIDataDetectorTypePhoneNumber;   
    return [ super webViewDidStartLoad:theWebView ];
}

// ...

UIWebView dataDetectorTypes example.
NSString *webViewBody = [[body stringByReplacingOccurrencesOfString:@"\t"       withString:@" "] stringByReplacingOccurrencesOfString:@"\n" withString:@"
"];

NSString *str = [NSString stringWithFormat:@"

 %@ 
",body];
        [webView loadHTMLString:webViewBody baseURL:nil];

        webView.dataDetectorTypes = UIDataDetectorTypeAll;

End of UIWebView dataDetectorTypes example article.