ios webview中二维码识别

来源:互联网 发布:linux坏了怎么卸载 编辑:程序博客网 时间:2024/05/19 03:26

网上查了些资料 但写的都不全,下面是自己实现成功的,做个记录。

////  ViewController.m//  day0421////  Created by 刘远超 on 16/4/21.//  Copyright © 2016年 刘远超. All rights reserved.//#import "ViewController.h"#import "ZXingObjC.h"#import "MBProgressHUD.h"@interface ViewController ()<UIWebViewDelegate,UIGestureRecognizerDelegate>{    UIWebView *MyWebView;    NSTimer *_timer;    // 用于UIWebView保存图片    int _gesState;    // 用于UIWebView保存图片    NSString *_imgURL;  // 用于UIWebView保存图片    NSString *_imgRWMURL; //二维码地址    NSString *_flag;}// 用于UIWebView保存图片enum{    GESTURE_STATE_NONE = 0,    GESTURE_STATE_START = 1,    GESTURE_STATE_MOVE = 2,    GESTURE_STATE_END = 4,    GESTURE_STATE_ACTION = (GESTURE_STATE_START | GESTURE_STATE_END),};@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    MyWebView = [[UIWebView alloc] initWithFrame:self.view.frame];    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://mp.weixin.qq.com/s?__biz=MjM5MDMyMTg0MQ==&mid=2664464373&idx=1&sn=d59bd1c6fe953a37c12e93f3f2e03797&scene=0#wechat_redirect"]];    [self.view addSubview: MyWebView];    [MyWebView loadRequest:request];    MyWebView.delegate = self;}- (void)webViewDidFinishLoad:(UIWebView *)webView{    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\";\    document.documentElement.style.webkitUserSelect='none';};";    // 防止内存泄漏    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];    [webView stringByEvaluatingJavaScriptFromString:kTouchJavaScriptString];    UILongPressGestureRecognizer * longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo)];    longPressGr.minimumPressDuration = 1.0;    longPressGr.delegate = self;    [webView addGestureRecognizer:longPressGr];}-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)_request navigationType:(UIWebViewNavigationType)navigationType {    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"])        {            _flag = nil;            if ([(NSString *)[components objectAtIndex:2] isEqualToString:@"start"])            {                _gesState = GESTURE_STATE_START;                float ptX = [[components objectAtIndex:3]floatValue];                float ptY = [[components objectAtIndex:4]floatValue];//                NSLog(@"touch point (%f, %f)", ptX, ptY);                NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).tagName", ptX, ptY];                NSString * tagName = [webView stringByEvaluatingJavaScriptFromString:js];                _imgURL = nil;                if ([tagName isEqualToString:@"IMG"]) {                    _imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", ptX, ptY];                }                if (_imgURL) {                    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(handleLongTouch) userInfo:nil repeats:NO];                }            }            else if ([(NSString *)[components objectAtIndex:2] isEqualToString:@"move"])            {                //**如果touch动作是滑动,则取消hanleLongTouch动作**//                _gesState = GESTURE_STATE_MOVE;//                NSLog(@"you are move");            }        }        else if ([(NSString*)[components objectAtIndex:2]isEqualToString:@"end"]) {            [_timer invalidate];            _timer = nil;            _gesState = GESTURE_STATE_END;//            NSLog(@"touch end");        }        return NO;    }    return YES;}//长按方法-(void)longPressToDo{    if (_imgURL &&_flag&& _gesState == GESTURE_STATE_START) {        NSString *urlToSave = [MyWebView stringByEvaluatingJavaScriptFromString:_imgURL];        NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlToSave]];        UIImage* img = [UIImage imageWithData:data];        [self CheckImage:img];    }}//如果点击的是图片,处理操作。- (void)handleLongTouch {    _flag = @"1";}/** * 识别图片中的二维码 */-(void)CheckImage:(UIImage *)img{    UIImage *loadImage= img;    CGImageRef imageToDecode = loadImage.CGImage;    // Given a CGImage in which we are looking for barcodes    ZXLuminanceSource *source = [[ZXCGImageLuminanceSource alloc] initWithCGImage:imageToDecode];    ZXBinaryBitmap *bitmap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];    NSError *error = nil;    _imgRWMURL = nil;    ZXDecodeHints *hints = [ZXDecodeHints hints];    ZXMultiFormatReader *reader = [ZXMultiFormatReader reader];    ZXResult *result = [reader decode:bitmap hints:hints error:&error];    UIAlertController* alertSheetController = [[UIAlertController alloc] init];    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *  action) {//        NSLog(@"取消");    }];    UIAlertAction* goURLAction = [UIAlertAction actionWithTitle:@"识别二维码" style:UIAlertActionStyleDefault handler:^(UIAlertAction *  action) {//        NSLog(@"识别二维码");        if (_imgRWMURL) {            NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:_imgRWMURL]];            [MyWebView loadRequest:request];        }    }];    UIAlertAction* saveImgAction = [UIAlertAction actionWithTitle:@"保存图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction *  action) {//        NSLog(@"保存图片");    }];    if (result) {        NSString *contents = result.text;        _imgRWMURL = contents;        [alertSheetController addAction:cancelAction];        [alertSheetController addAction:goURLAction];        [alertSheetController addAction:saveImgAction];    } else {        [alertSheetController addAction:cancelAction];        [alertSheetController addAction:saveImgAction];    }    [self presentViewController:alertSheetController animated:YES completion:nil];}/** *  必须写 否则长按手势无效 */- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{    return YES;}@end
0 0
原创粉丝点击