IOS native two-dimensional code scanning _ios

Source: Internet
Author: User

To do a two-dimensional code scan of iOS, there are two third-party libraries to choose from, Zbar and zxing. Today we are going to introduce the native two-dimensional code scan provided by the iOS7.0 avfoundation framework.

First you need to add the Avfoundation.framework framework to the build phase in your project "Link Binary with Libraries", and then you can start.

First, prepare to work, build UI

UI effects as shown

Iboutlet and Ibaction are as follows:

@property (Weak, nonatomic) Iboutlet UIView *viewpreview;
@property (Weak, nonatomic) Iboutlet Uilabel *lblstatus;
@property (Weak, nonatomic) Iboutlet UIButton *startbtn;
-(Ibaction) startstopreading: (ID) sender;

Then it's all about the code.

Second, the controller ViewController.h

First import the Avfoundation framework

#import <AVFoundation/AVFoundation.h>

Then the Controller realizes the Avcapturemetadataoutputobjectsdelegate protocol

@interface Viewcontroller () <AVCaptureMetadataOutputObjectsDelegate>

The overall property is as follows:

@property (Strong, nonatomic) UIView *boxview;
@property (nonatomic) BOOL isreading;
@property (Strong, nonatomic) Calayer *scanlayer;
-(BOOL) startreading;
-(void) stopreading;

Capture session

@property (nonatomic, strong) avcapturesession *capturesession;

Show Layer

@property (nonatomic, strong) Avcapturevideopreviewlayer *videopreviewlayer;

It is then initialized in the Viewdidload method.

-(void) viewdidload {
  [super viewdidload];

  _capturesession = nil;
   _isreading = NO;
  
}

The next step is to implement the Startreading method (which is the point)

-(BOOL) startreading {nserror *error; 1. Initialize the capture device (Avcapturedevice), the type is avmediatypevideo avcapturedevice *capturedevice = [Avcapturedevice
 Defaultdevicewithmediatype:avmediatypevideo]; 2. Create input stream with capturedevice avcapturedeviceinput *input = [Avcapturedeviceinput deviceinputwithdevice:capturedevice
 error:&error];
  if (!input) {NSLog (@ "%@", [Error localizeddescription]);
 return NO;
 //3. Create media data output stream avcapturemetadataoutput *capturemetadataoutput = [[Avcapturemetadataoutput alloc] init];
 4. Materialized capture Session _capturesession = [[Avcapturesession alloc] init];
 4.1. Add the input stream to the session [_capturesession Addinput:input];
 4.2. Add the media output stream to the session [_capturesession Addoutput:capturemetadataoutput];
 5. Create a serial queue and add the media output stream to the queue dispatch_queue_t dispatchqueue;
 Dispatchqueue = Dispatch_queue_create ("Myqueue", NULL);
 5.1. Set up Agent [Capturemetadataoutput setmetadataobjectsdelegate:self queue:dispatchqueue]; 5.2. Set the output media data type QRCode [Capturemetadataoutput setmetadataobjecttypes:[nsarray Arraywithobject:avmeTadataobjecttypeqrcode]];
 6. Materialized preview Layer _videopreviewlayer = [[Avcapturevideopreviewlayer alloc] initwithsession:_capturesession];
 7. Set preview layer fill mode [_videopreviewlayer Setvideogravity:avlayervideogravityresizeaspectfill];
 8. Set the layer frame [_videopreviewlayer setframe:_viewpreview.layer.bounds];
 9. Add layers to the layer on the Preview view [_viewpreview.layer Addsublayer:_videopreviewlayer];
 10. Set Scan Range capturemetadataoutput.rectofinterest = CGRectMake (0.2f, 0.2f, 0.8f, 0.8f); 10.1. Scan frame _boxview = [[UIView alloc] Initwithframe:cgrectmake (_viewpreview.bounds.size.width * 0.2f, _ ViewPreview.bounds.size.height * 0.2f, _viewpreview.bounds.size.width-_viewpreview.bounds.size.width * 0.4f, _
 ViewPreview.bounds.size.height-_viewpreview.bounds.size.height * 0.4f)]; _boxview.layer.bordercolor = [Uicolor Greencolor].
 Cgcolor;
 _boxview.layer.borderwidth = 1.0f;
 [_viewpreview Addsubview:_boxview];
 10.2. Scan line _scanlayer = [[Calayer alloc] init]; _scanlayer.frame = CGRectMake (0, 0, _boxview.bounds.size.width, 1); _scanlayer.backgroundcolor = [Uicolor Browncolor].
 Cgcolor;
 [_boxview.layer Addsublayer:_scanlayer]; Nstimer *timer = [Nstimer scheduledtimerwithtimeinterval:0.2f target:self selector: @selector (movescanlayer:) userInfo
 : Nil Repeats:yes];

 [Timer fire];
 10. Start scanning [_capturesession startrunning];
return YES; }

Implementation of Avcapturemetadataoutputobjectsdelegate protocol method

#pragma mark-avcapturemetadataoutputobjectsdelegate
-(void) Captureoutput: (Avcaptureoutput *) captureoutput Didoutputmetadataobjects: (Nsarray *) metadataobjects fromconnection: (avcaptureconnection *) connection
{
 // Determine if there is data if
 (metadataobjects!= nil && [metadataobjects count] > 0) {
  Avmetadatamachinereadablecodeobject *metadataobj = [metadataobjects objectatindex:0];
  Determines the data type of the postback
  if ([[Metadataobj type] isequaltostring:avmetadataobjecttypeqrcode]) {
   [_lblstatus Performselectoronmainthread: @selector (setText:) withobject:[metadataobj stringvalue] waituntildone:no];
   [Self Performselectoronmainthread: @selector (stopreading) Withobject:nil Waituntildone:no];
   _isreading = NO;}}

Implement Timer Method Movescanlayer: (Nstimer *) timer

-(void) Movescanlayer: (Nstimer *) timer
{
 CGRect frame = _scanlayer.frame;
 if (_boxview.frame.size.height < _SCANLAYER.FRAME.ORIGIN.Y) {
  frame.origin.y = 0;
  _scanlayer.frame = frame;
 } else{
  FRAME.ORIGIN.Y + + 5;
  [UIView animatewithduration:0.1 animations:^{
   _scanlayer.frame = frame;
  }];
 }

Implementing Start and Stop methods

-(Ibaction) startstopreading: (ID) Sender {
  if (!_isreading) {
   if ([self startreading]) {
    [_startbtn settitle:@ "Stop" forstate:uicontrolstatenormal];
    [_lblstatus settext:@ "Scanning for QR Code"];
   }
  else{
   [self stopreading];
   [_startbtn settitle:@ "start!" forstate:uicontrolstatenormal];
  }
  _isreading =!_isreading;
}
-(void) stopreading{
 [_capturesession stoprunning];
 _capturesession = nil;
 [_scanlayer Removefromsuperlayer];
 [_videopreviewlayer Removefromsuperlayer];
}

The above content is this article to introduce the iOS native two-dimensional code scan all content, hoped everybody likes.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.