简体   繁体   English

在Safari中打开WebView链接

[英]Open WebView links in Safari

When Running the app it first loads, then loads the web page in safari. 在运行该应用程序时,它会先加载,然后再在Safari中加载网页。 How would I make the page load in the UIWebView and have the external links in the webView open in safari? 如何在UIWebView加载页面并如何在Safari中打开webView的外部链接?

Here is some of the Code of The webviewcontroller.m - 这是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: 第一行代码加载到Safari中而不是应用程序中的UIWebView的原因是以下代码行:

[[UIApplication sharedApplication] openURL:url];

Remove this line from your viewDidLoad method. viewDidLoad方法中删除此行。

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; 为了在Safari应用程序中的webView加载链接,请首先使用webView.delegate = self;将视图控制器设置为webView的委托webView.delegate = self; inside the viewDidLoad method. viewDidLoad方法中。

Then add the following code to your viewController : 然后将以下代码添加到您的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. 每当webView即将开始加载请求时,都会调用此方法。 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. 如果是这样,它将打开Safari并在其中加载请求。 Any other requests that were not initiated by a click are loaded within your application, such as the request for your start page. 并非通过单击启动的任何其他请求都将加载到您的应用程序中,例如对起始页的请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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