如何在UIWebView中获取检测到的数字

时间:2013-12-06 11:35:18

标签: ios objective-c uiwebview phone-number tel

是否有可能在UIWebView中检测到号码。

当我在iPad上点击UIWebView中的数字时,我会看到以下选项:

发送消息,添加到联系人,复制。

如何删除该弹出窗口并获取检测到的号码?

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,100,1024,768)];
webView.dataDetectorTypes = UIDataDetectorTypePhoneNumber; 
NSURL *url = [NSURL URLWithString:@"somepage"]; 
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url]; 
[webView loadRequest:urlRequest]; 

UIWebView检测到电话号码,当我点击号码时,系统会显示popover。

有趣的是,当我点击数字时,没有调用任何UIWebViewDelegate方法。

我只需要检测到号码。

2 个答案:

答案 0 :(得分:1)

停止检测数字并将其作为链接。因此,当您按下链接(数字)时,它将带您进入shouldStartLoadWithRequest方法。

下面的代码应该有助于我详细说明如果您需要其他任何问题,每行的功能。

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
                                        navigationType:(UIWebViewNavigationType)navigationType
{
    static NSString *urlPrefix = @"tel://";
    NSString *url = [[request url] absoluteString]; // Notice that we are getting the obsoluteString of the url 
    if([url hasPrefix:urlPrefix]) { // We then check that the url has a prefix of our urlPrefix otherwise why bother doing anything at all.
       if([[UIApplication sharedApplication] canOpenUrl:url]) { // This is to check that we can actually open a url as iPads can't make phone calls.
           [[UIApplication sharedApplication] openUrl:url]; // And if everything is successful we are good to make the phone call.
           return NO; // We don't want the UIWebView to go navigating somewhere crazy so tell it to stop navigating away.
       } else {
           return NO; // If it does contain the prefix but we can't open the url we don't want to navigate away so return NO.
       }
    }

    return YES; // If all else fails it most be a standard request so return YES.
}

代码将在以下链接上运行:

<p>Call us on:<a href="tel://12345678900">12345678900</a></p>

<强>更新

我刚刚意识到你没有设置你的webView代表。所以在你的.h文件中确保你有:

@interface MyClassName : MySuperClass <UIWebViewDelegate> // Obviously 'MyClassName' and MySuperClass' you need to replace with your classes.

然后在UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,100,1024,768)];之后你需要做[webView setDelegate:self];这将设置它以便它应该使用委托方法。

如果您还有其他问题,请发表评论。

答案 1 :(得分:-1)

使用以下委托方法检测电话号码:

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
                                            navigationType:(UIWebViewNavigationType)navigationType
{
     if ([url.scheme isEqualToString:@"tel"])
     {
         [[UIApplication sharedApplication] openURL:url];
     }
}

以下是参考帖子:UIWebView doesn't detect phone number links