天天看點

ios 二維碼掃描(微信二維碼掃描音效)

非常感謝大家利用自己寶貴的時間來閱讀我的文章 ,  今天給大家帶來的是一個原生二維碼掃描的demo,很久之前寫的代碼,最近項目要用,想着以後用到的可能性也挺大的,就翻出來整理了個demo出來,如果需要的可以做個參考。如果需要的話希望能幫到你 , 當然, 有任何不妥的地方 歡迎指正。喜歡的可以關注一下我的部落格、我的簡書

老規矩,先上效果展示

ios 二維碼掃描(微信二維碼掃描音效)

卧槽,這個gif為何如此之大。。。不管了,上demo位址ZQScanTool

用法很簡單,把ZQScanTool檔案夾拖入到項目中,在需要跳轉掃描的時候把ScanViewController給Push出來

ScanViewController *vc = [[ScanViewController alloc] init];

    [self.navigationController pushViewController:vc animated:YES];
           

把掃描結果展示控制器ScanResultViewController換成你的調轉頁

到這裡就不用看了,下demo去吧。。。

主要代碼:

1、相機設定

- (void)instanceDevice{



    line_tag = 1872637;

    //擷取攝像裝置

    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    //建立輸入流

    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];

    //建立輸出流

    AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];

    //設定代理 在主線程裡重新整理

    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];



    //初始化連結對象

    session = [[AVCaptureSession alloc]init];

    //高品質采集率

    [session setSessionPreset:AVCaptureSessionPresetHigh];

    if (input) {

        [session addInput:input];

    }

    if (output) {

        [session addOutput:output];

        //設定掃碼支援的編碼格式(如下設定條形碼和二維碼相容)

        NSMutableArray *a = [[NSMutableArray alloc] init];

        if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeQRCode]) {

            [a addObject:AVMetadataObjectTypeQRCode];

        }

        if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeEAN13Code]) {

            [a addObject:AVMetadataObjectTypeEAN13Code];

        }

        if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeEAN8Code]) {

            [a addObject:AVMetadataObjectTypeEAN8Code];

        }

        if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeCode128Code]) {

            [a addObject:AVMetadataObjectTypeCode128Code];

        }

        output.metadataObjectTypes=a;

    }

    AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:session];

    layer.videoGravity=AVLayerVideoGravityResizeAspectFill;

    layer.frame=self.view.layer.bounds;

    [self.view.layer insertSublayer:layer atIndex:0];



    [self setOverlayPickerView];



    [session addObserver:self forKeyPath:@"running" options:NSKeyValueObservingOptionNew context:nil];



    //開始捕獲

    [session startRunning];

}
           

2、掃描UI

- (void)setOverlayPickerView

{

    //左側的view

    UIImageView *leftView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, ScreenHeight)];

    leftView.alpha = 0.5;

    leftView.backgroundColor = [UIColor blackColor];

    [self.view addSubview:leftView];

    //右側的view

    UIImageView *rightView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth-30, 0, 30, ScreenHeight)];

    rightView.alpha = 0.5;

    rightView.backgroundColor = [UIColor blackColor];

    [self.view addSubview:rightView];

    //最上部view

    UIImageView* upView = [[UIImageView alloc] initWithFrame:CGRectMake(30, 0, ScreenWidth - 60, (self.view.center.y-(ScreenWidth-60)/2))];

    upView.alpha = 0.5;

    upView.backgroundColor = [UIColor blackColor];

    [self.view addSubview:upView];

    UIButton *cancleBtn = [[UIButton alloc] initWithFrame:CGRectMake(5, 20, 44, 44)];

    [cancleBtn setImage:[UIImage imageNamed:@"nav_backButton_image"] forState:UIControlStateNormal];

    [cancleBtn addTarget:self action:@selector(cancleBtnClick) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:cancleBtn];

    //底部view

    UIImageView * downView = [[UIImageView alloc] initWithFrame:CGRectMake(30, (self.view.center.y+(ScreenWidth-60)/2), (ScreenWidth-60), (ScreenHeight-(self.view.center.y-(ScreenWidth-60)/2)))];

    downView.alpha = 0.5;

    downView.backgroundColor = [UIColor blackColor];

    [self.view addSubview:downView];

    UIImageView *centerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth-60, ScreenHeight-60)];

    centerView.center = self.view.center;

    centerView.image = [UIImage imageNamed:@"scan_circle"];

    centerView.contentMode = UIViewContentModeScaleAspectFit;

    centerView.backgroundColor = [UIColor clearColor];

    [self.view addSubview:centerView];

    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(30, CGRectGetMaxY(upView.frame), ScreenWidth-60, 2)];

    line.tag = line_tag;

    line.image = [UIImage imageNamed:@"scan_line"];

    line.contentMode = UIViewContentModeScaleAspectFill;

    line.backgroundColor = [UIColor clearColor];

    [self.view addSubview:line];

    UILabel *msg = [[UILabel alloc] initWithFrame:CGRectMake(30, CGRectGetMinY(downView.frame), ScreenWidth-60, 60)];

    msg.backgroundColor = [UIColor clearColor];

    msg.textColor = [UIColor whiteColor];

    msg.textAlignment = NSTextAlignmentCenter;

    msg.font = [UIFont systemFontOfSize:16];

    msg.text = @"将二維碼放入框内,即可自動掃描";

    [self.view addSubview:msg];

}
           

3、掃描動畫

/**

*

*  監聽掃碼狀态-修改掃描動畫

*

*/

- (void)observeValueForKeyPath:(NSString *)keyPath

                      ofObject:(id)object

                        change:(NSDictionary *)change

                      context:(void *)context{

    if ([object isKindOfClass:[AVCaptureSession class]]) {

        BOOL isRunning = ((AVCaptureSession *)object).isRunning;

        if (isRunning) {

            [self addAnimation];

        }else{

            [self removeAnimation];

        }

    }

}
           

*  添加掃碼動畫

- (void)addAnimation{

    UIView *line = [self.view viewWithTag:line_tag];

    line.hidden = NO;

    CABasicAnimation *animation = [ScanViewController moveYTime:2 fromY:[NSNumber numberWithFloat:0] toY:[NSNumber numberWithFloat:ScreenWidth-60-2] rep:OPEN_MAX];

    [line.layer addAnimation:animation forKey:@"LineAnimation"];

}
           

  * 去除掃碼動畫

- (void)removeAnimation{

    UIView *line = [self.view viewWithTag:line_tag];

    [line.layer removeAnimationForKey:@"LineAnimation"];

    line.hidden = YES;

}
           
+ (CABasicAnimation *)moveYTime:(float)time fromY:(NSNumber *)fromY toY:(NSNumber *)toY rep:(int)rep

{

    CABasicAnimation *animationMove = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];

    [animationMove setFromValue:fromY];

    [animationMove setToValue:toY];

    animationMove.duration = time;

    animationMove.delegate = self;

    animationMove.repeatCount  = rep;

    animationMove.fillMode = kCAFillModeForwards;

    animationMove.removedOnCompletion = NO;

    animationMove.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

    return animationMove;

}
           

3、掃描結果

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{

    if (metadataObjects.count>0) {

        [session stopRunning];

        NSURL *url=[[NSBundle mainBundle]URLForResource:@"scanSuccess.wav" withExtension:nil];

            //2.加載音效檔案,建立音效ID(SoundID,一個ID對應一個音效檔案)

            SystemSoundID soundID=8787;

            AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);

            //3.播放音效檔案

            //下面的兩個函數都可以用來播放音效檔案,第一個函數伴随有震動效果

            AudioServicesPlayAlertSound(soundID);

        AudioServicesPlaySystemSound(8787);

        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex :0];

        //輸出掃描字元串

        NSString *data = metadataObject.stringValue;

        ScanResultViewController *resultVC = [[ScanResultViewController alloc] init];

        resultVC.title = @"掃描結果";

        resultVC.result = data;

        [self.navigationController pushViewController:resultVC animated:YES];

    }

}
           

@#%¥¥#&……¥#@!#!@¥@#%¥¥!@#!@#!說了不用看了,恩,就這麼多了。好用别忘了點贊!