如何使用UIWebView Delegate的shouldStartLoadWithRequest方法

时间:2013-03-04 03:31:09

标签: ios objective-c uiwebview uiwebviewdelegate

我需要从UIWebView中显示的URL中删除超链接,我已经查看了这个问题:Removing hyper links from a URL shown in UIWebView

我知道我需要使用这种方法:

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

但我似乎还有一些问题。

首先,我如何避免某些链接(例如:www.google.com)。

接下来,我如何避免UIWebView中的所有链接?

我的代码如下所示:

[webUI loadHTMLString:[strDescription stringByDecodingHTMLEntities] baseURL:nil];
webUI.dataDetectorTypes = UIDataDetectorTypeNone;

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"finish loading");

    [webUI stringByEvaluatingJavaScriptFromString:@"document.styleSheets[0].addRule(\".active\", \"pointer-events: none;\");document.styleSheets[0].addRule(\".active\", \"cursor: default;\")"];

}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
       return YES;
}

需要一些指导。感谢..

HTML字符串如下所示:

> <div style="font-family: Helvetica"><div style="color: #FFFFFF;"><div
> style="font-family: Helvetica;"><p><span style="font-size:
> 24px;"><strong>Optimal Performance Always</strong></span><span
> style="font-size: 18px;"><br /></span></p><p><span style="font-size:
> 18px;">The standard servicing package<a
> href="http://www.google.com">www.google.com</a></div>

1 个答案:

答案 0 :(得分:3)

如果要在加载第一页后禁用所有链接,可以在页面加载时添加属性以存储并在webView上使用其值:shouldStartLoadWithRequest:

@property(nonatomic) BOOL pageLoaded; // initially NO

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"finish loading");

    [webUI stringByEvaluatingJavaScriptFromString:@"document.styleSheets[0].addRule(\".active\", \"pointer-events: none;\");document.styleSheets[0].addRule(\".active\", \"cursor: default;\")"];

    // after all your stuff
    self.pageLoaded = YES;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
   return ! self.pageLoaded;
}

请注意,这不会隐藏链接,只会使webview无法加载它们。

此外,您可以在webView上检查request.URL:shouldStartLoadWithRequest:navigationType:仅加载某些页面。另一种方法是检查navigationType值:

enum {
   UIWebViewNavigationTypeLinkClicked,
   UIWebViewNavigationTypeFormSubmitted,
   UIWebViewNavigationTypeBackForward,
   UIWebViewNavigationTypeReload,
   UIWebViewNavigationTypeFormResubmitted,
   UIWebViewNavigationTypeOther
};