欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS实现二维码的扫描功能

程序员文章站 2022-03-23 13:13:13
直接上代码,就不多废话了 // // viewcontroller.m // qrcode // // created by chenchen on 15...

直接上代码,就不多废话了

//
// viewcontroller.m
// qrcode
//
// created by chenchen on 15/7/30.
// copyright (c) 2015年 bsy. all rights reserved.
//
#import <avfoundation/avfoundation.h>
#import "viewcontroller.h"
@interface viewcontroller ()<avcapturemetadataoutputobjectsdelegate>
 
@end
 
@implementation viewcontroller
 
- (void)viewdidload {
  [super viewdidload];
  
   
   
  avcapturesession *session = [[avcapturesession alloc] init];
  avcapturedevice *device = [avcapturedevice defaultdevicewithmediatype:avmediatypevideo];
  nserror *error = nil;
   
  avcapturedeviceinput *input = [avcapturedeviceinput deviceinputwithdevice:device
                                    error:&error];
  if (input) {
    [session addinput:input];
  } else {
    nslog(@"error: %@", error);
  }
  avcapturemetadataoutput *output = [[avcapturemetadataoutput alloc] init];
  //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
  [output setmetadataobjecttypes:@[avmetadataobjecttypeqrcode,avmetadataobjecttypeean13code, avmetadataobjecttypeean8code, avmetadataobjecttypecode128code]];
  [output setmetadataobjectsdelegate:self queue:dispatch_get_main_queue()];
  [session addoutput:output];
  [session startrunning];
}
 
#pragma mark - avcapturemetadataoutputobjectsdelegate
- (void)captureoutput:(avcaptureoutput *)captureoutput
didoutputmetadataobjects:(nsarray *)metadataobjects
    fromconnection:(avcaptureconnection *)connection
{
  nsstring *qrcode = nil;
  for (avmetadataobject *metadata in metadataobjects) {
    if ([metadata.type isequaltostring:avmetadataobjecttypeqrcode]) {
      // this will never happen; nobody has ever scanned a qr code... ever
      qrcode = [(avmetadatamachinereadablecodeobject *)metadata stringvalue];
      break;
    }
  }
   
  nslog(@"qr code: %@", qrcode);
}
- (void)didreceivememorywarning {
  [super didreceivememorywarning];
  // dispose of any resources that can be recreated.
}
 
@end