iOS UIWebView 二维码识别

本文介绍如何在iOS应用中使用WebView加载网页,并通过两种方法实现图片长按功能,包括识别图片中的二维码、保存图片等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.第一种方法,在代理中加入js实现该功能 .在webview的代理方法中实现

#pragma mark UIWebViewDelegate 方法
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // 标题不存在时从网页获取
    if (!self.title) {
        NSString *htmlTitle = @"document.title";
        self.title = [_webView stringByEvaluatingJavaScriptFromString:htmlTitle];
    }

    //  add by zcj 实现图片长按识别功能
    static NSString* const kTouchJavaScriptString=
    @"document.ontouchstart=function(event){\
    x=event.targetTouches[0].clientX;\
    y=event.targetTouches[0].clientY;\
    document.location=\"myweb:touch:start:\"+x+\":\"+y;};\
    document.ontouchmove=function(event){\
    x=event.targetTouches[0].clientX;\
    y=event.targetTouches[0].clientY;\
    document.location=\"myweb:touch:move:\"+x+\":\"+y;};\
    document.ontouchcancel=function(event){\
    document.location=\"myweb:touch:cancel\";};\
    document.ontouchend=function(event){\
    document.location=\"myweb:touch:end\";};";
    [webView stringByEvaluatingJavaScriptFromString:kTouchJavaScriptString];//注入js方法

    // ]end
}
#pragma mark UIWebViewDelegate 方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (![request.URL.absoluteString isEqualToString:_url])
    {
        [_backButton setHidden:NO];
    }


    // add by zcj 实现图片长按识别功能
    NSString *requestString =  request.URL.absoluteString;

     NSArray *components = [requestString componentsSeparatedByString:@":"];
     if ([components count] > 1 && [(NSString *)[components objectAtIndex:0]
     isEqualToString:@"myweb"]) {
     if([(NSString *)[components objectAtIndex:1] isEqualToString:@"touch"])
     {
     //NSLog(@"you are touching!");
     if ([(NSString *)[components objectAtIndex:2] isEqualToString:@"start"])
     {
     _gesState = UIGestureRecognizerStateBegan;

     float ptX  =[[components objectAtIndex:3]floatValue];
     float ptY =[[components objectAtIndex:4]floatValue];

     NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).tagName", ptX, ptY];
     NSString * tagName = [self.webView stringByEvaluatingJavaScriptFromString:js];

     if ([tagName isEqualToString:@"IMG"]) {
     self.imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", ptX, ptY];
     }
     if (self.imgURL) {

     [self performSelector:@selector(handleLongTouch) withObject:nil afterDelay:1.0];

     }
     }
     else if ([(NSString *)[components objectAtIndex:2] isEqualToString:@"move"])
     {

     _gesState = UIGestureRecognizerStateChanged;

     }
     }
     else if ([(NSString*)[components objectAtIndex:2]isEqualToString:@"end"]) {

     _gesState = UIGestureRecognizerStateEnded;

     }
     }// ]end

    return YES;
}
// add by zcj
#pragma mark 实现图片长按识别二维码
- (void)handleLongTouch {

    if (self.imgURL && _gesState == UIGestureRecognizerStateBegan) {

        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

        NSString *urlToSave = [self.webView stringByEvaluatingJavaScriptFromString:self.imgURL];

        NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlToSave]];
        UIImage* image = [UIImage imageWithData:data];

        NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:
                                 @"CIDetectorAccuracy", @"CIDetectorAccuracyHigh",nil];
        CIDetector *detector = nil;
        if (IOS8_Later)// 宏定义在pct文件中,这里用[[UIDevice currentDevice].systemVersion floatValue] >= 8.0替换
            detector = [CIDetector detectorOfType:CIDetectorTypeQRCode
                                          context:nil
                                          options:options];
        NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]] ;

        // 识别图中二维码
        UIAlertAction *judgeCode = [UIAlertAction actionWithTitle:@"识别图中二维码" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            CIQRCodeFeature *feature = [features objectAtIndex:0];
            NSString *scannedResult = feature.messageString;

            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:scannedResult]]){
                // 在这里打开这个网址,注意这个scannedResult是string类型。以下是我自己项目里的网页控制器
              /*
                WebBrowser *webBrowser = [[WebBrowser alloc] initWithNibName:@"WebBrowser" bundle:[Util mainBundle]];
                [webBrowser loadWebWithTitle:nil urlAddress:scannedResult];
                [self.navigationController pushViewController:webBrowser animated:YES];
                [webBrowser release];
                */
            }else{
                [Util Alert:@"无法识别的网址" title:@"温馨提示"];
            }
        }];

        // 保存图片到手机
        UIAlertAction *saveImage = [UIAlertAction actionWithTitle:@"保存到手机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }];

        // 取消
        UIAlertAction *cancell = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        }];


        if (features.count >= 1) {
            [alertController addAction:judgeCode];
        }

        [alertController addAction:saveImage];
        [alertController addAction:cancell];
        [self presentViewController:alertController animated:YES completion:nil];

    }
} // ]end

2.第二种方法,通过添加长按手势,结合js实现该功能

// 首先,在代理方法中为改webview添加长按手势

- (void)webViewDidFinishLoad:(UIWebView *)webView
{

    // add by zcj 实现图片长按识别功能
    UILongPressGestureRecognizer* longPressed = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
    longPressed.delegate = self;
    [self.webView addGestureRecognizer:longPressed];
    // ]end

}

// add by zcj 长按识别图中二维码
- (void)longPressed:(UILongPressGestureRecognizer*)recognizer
{
    if (recognizer.state != UIGestureRecognizerStateBegan) {
        return;
    }

    CGPoint touchPoint = [recognizer locationInView:self.webView];
    // 获取手势所在图片的URL,js中图片的地址是用src引用的
    NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
    NSString *urlToSave = [self.webView stringByEvaluatingJavaScriptFromString:imgURL];

    if (urlToSave.length == 0) {
        return;
    }

    [self showImageOptionsWithUrl:urlToSave];
}

// 然后,根据获得的图片URL进行相应的操作

- (void)showImageOptionsWithUrl:(NSString *)imgURL
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgURL]];
    UIImage* image = [UIImage imageWithData:data];

    NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:
                             @"CIDetectorAccuracy", @"CIDetectorAccuracyHigh",nil];
    CIDetector *detector = nil;
    if (IOS8_Later)
        detector = [CIDetector detectorOfType:CIDetectorTypeQRCode
                                      context:nil
                                      options:options];
    NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];

    // 识别图中二维码
    UIAlertAction *judgeCode = [UIAlertAction actionWithTitle:@"识别图中二维码" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        CIQRCodeFeature *feature = [features objectAtIndex:0];
        NSString *scannedResult = feature.messageString;

        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:scannedResult]]){
            // 这里和第一种方法一样,根据scannedResult做相应的操作即可。下面是我项目中的浏览器控制器打开这个网页。
            WebBrowser *webBrowser = [[WebBrowser alloc] initWithNibName:@"WebBrowser" bundle:[Util mainBundle]];
            [webBrowser loadWebWithTitle:nil urlAddress:scannedResult];
            [self.navigationController pushViewController:webBrowser animated:YES];
            [webBrowser release];

        }else{
            [Util Alert:@"无法识别的网址" title:@"温馨提示"];
        }
    }];

    // 保存图片到手机
    UIAlertAction *saveImage = [UIAlertAction actionWithTitle:@"保存图片到手机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }];

    // 取消
    UIAlertAction *cancell = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

    }];


    if (features.count >= 1) {
        [alertController addAction:judgeCode];
    }

    [alertController addAction:saveImage];
    [alertController addAction:cancell];
    [self presentViewController:alertController animated:YES completion:nil];

}
// 功能:显示图片保存结果
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
    if (error){
        [Util Alert:@"保存图片失败" title:@"温馨提示"];
    }else {
      // 这一句仅仅是提示保存成功
        [CJUtil showInBottomWithTitle:@"保存成功" backgroundColor:nil textColor:nil];
    }
}
// ]end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值