在 Safari 中打开 WebView 链接 [英] Open WebView links in Safari

查看:35
本文介绍了在 Safari 中打开 WebView 链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行应用程序时,它首先加载,然后在 safari 中加载网页.如何在 UIWebView 中加载页面并在 safari 中打开 webView 中的外部链接?

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?

这是webviewcontroller.m的一些代码 -

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

推荐答案

在 Safari 中加载第一页而不是应用程序中的 UIWebView 的原因是这行代码:

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];

从您的 viewDidLoad 方法中删除这一行.

Remove this line from your viewDidLoad method.

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

然后将以下代码添加到您的 viewController:

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;
}

每次 webView 即将开始加载请求时,都会调用此方法.它所做的是检查请求是否是由用户点击发起的.如果是,它会打开 Safari 并在那里加载请求.不是由点击发起的任何其他请求都会加载到您的应用程序中,例如对您的起始页的请求.

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.

这篇关于在 Safari 中打开 WebView 链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆