简体   繁体   中英

Open WebView links in Safari

When Running the app it first loads, then loads the web page in safari. How would I make the page load in the UIWebView and have the external links in the webView open in safari?

Here is some of the Code of The webviewcontroller.m -

#import "WebViewController.h"


@implementation WebViewController

@synthesize webView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
    // Initialization code
}
return self;
}

/*
 If you need to do additional setup after loading the view, override viewDidLoad. */
- (void)viewDidLoad {

NSString *urlAddress = @"url link goes here";

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

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

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

@end

The reason the first page is loading in Safari instead of your UIWebView in your app is this line of code:

[[UIApplication sharedApplication] openURL:url];

Remove this line from your viewDidLoad method.

In order to make links inside your webView load in the Safari app, first set your view controller as the delegate for the webView with webView.delegate = self; inside the viewDidLoad method.

Then add the following code to your viewController :

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

    if (navigationType == UIWebViewNavigationTypeLinkClicked)
    {
        [[UIApplication sharedApplication] openURL:request.URL];
        return NO;
    }
    return YES;
}

This method will get called every time the webView is about to start loading a request. What it does is check if the request was initiated by a click by the user. In case it was, it opens Safari and loads the request there. Any other requests that were not initiated by a click are loaded within your application, such as the request for your start page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM