Search code examples
uiwebviewiphone-5ios7

create a InApp browser implementation in iOS app


I have a requirement were in i have to create a view to display webpages with back, forward and refresh button in iOS app. how to implement this functionality?


Solution

  • Use UIWebView. Set the delegate to the view controller.

    self.webView.delegate = self;
    

    Other remarkable properties,

    self.webView.scalesPageToFit = YES;
    

    To load a URLRequest,

    [self.webView loadRequest:theRequest];
    

    or for only strings, use

    [self.webView loadHTMLString:htmlString baseURL:nil];
    

    And some delegates here. web view has its own history, you can use it by calling its back and forward methods.

    #pragma mark - UIWebView delegate
    
    // You can handle your own url scheme or let the web view handle it.
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
            navigationType:(UIWebViewNavigationType)navigationType
    {
        NSLog(@"url=%@, %@, %@",
              request.URL, request.URL.query, request.URL.host);
    
        if (navigationType == UIWebViewNavigationTypeLinkClicked) {     
            if ([request.URL.scheme compare:@"customescheme"] == NSOrderedSame) {
                if ([request.URL.host compare:kSomethingDotCom] == NSOrderedSame) {
                    [self mymethod];
                } else if ([request.URL.host compare:kAnotherDotCom] == NSOrderedSame) {
                    [self method2];
                } else {
                    NSLog(@"Unsupported service.");
                }
                return NO;
            }
        }
        return YES;
    }
    
    - (void)webViewDidFinishLoad:(UIWebView *)webView
    {
        [_activityIndicator stopAnimating];
    }
    
    - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
    {
        [_activityIndicator stopAnimating];
        [Resources showAlert:@"Could not load." withTitle:@"Error!"];
        NSLog(@"%@", [error localizedDescription]);
    }
    
    #pragma mark - Actions
    
    - (IBAction)didPressBackButton:(id)sender
    {
        [_webView goBack];
    }
    
    - (IBAction)didPressForwardButton:(id)sender
    {
        [_webView goForward];
    }
    

    Similarly you can have the stop method. To refresh reload the request again. Before going back or forward you can check the methods canGoBack or canGoForward. See docs at, http://developer.apple.com/library/ios/#documentation/uikit/reference/UIWebView_Class/Reference/Reference.html