IOS UIWebView:在safari中打开链接

时间:2012-11-08 15:15:47

标签: ios uiwebview

我创建了自定义类,文件是showBlock.h和showBlock.m,用于以编程方式加载UIWebView,showBlock.m的实现是

#import "showBlock.h"

@implementation showBlock;

@synthesize mainViewContObj;

- (void) showView {
    UIWebView *aWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
    aWebView.autoresizesSubviews = YES;
    aWebView.autoresizingMask = (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
    [aWebView setDelegate:[self mainViewContObj]];
    NSString *urlAddress = @"http://localhost/test/index.php";
    NSURL *url = [NSURL URLWithString:urlAddress];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

    [aWebView loadRequest:requestObj];

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    [[[self mainViewContObj] view] addSubview:aWebView];

}
@end

它工作正常,并加载带有html内容的index.php文件,但我想在safari浏览器中打开这个html文件的链接,我需要做些什么呢?

3 个答案:

答案 0 :(得分:11)

您需要在ShowBlock.m

中添加下面的委托方法实现
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType {
    // This practically disables web navigation from the webView.
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        [[UIApplication sharedApplication] openURL:[request URL]];
        return FALSE;
    }
    return TRUE;
}

答案 1 :(得分:1)

实施UIWebViewDelegate协议并设置aWebView.delegate = self

然后实施

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

单击链接时将调用此方法。从请求中获取URL。

使用以下代码在safari中打开链接:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @\"http://www.google.com"]];

答案 2 :(得分:1)

UIWebView委托中,定义webView:shouldStartLoadWithRequest方法:

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

    if ([[request URL] checkCondition]) 
       [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;
    }
    return YES;

}

checkCondition是一种方法,用于检查是否应通过safari打开URL(您可以根据域或其他方式进行检查)。在最简单的情况下,请始终致电openURL(删除if