Open WebView links in Safari

烈酒焚心 提交于 2019-12-11 18:09:08

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/15537289/open-webview-links-in-safari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!