IOS 7 apple native QR code scanning and iOS 7 Scanning

Source: Internet
Author: User

IOS 7 apple native QR code scanning and iOS 7 Scanning

In iOS 7, Apple launched a QR code scan. Previously, to scan a QR code, you can only use a third-party ZBar and ZXing.

ZBar is superior to ZXing in terms of scanning sensitivity and memory usage, but it is difficult to scan the "rounded QR code.

ZXing is an open-source barcode scanning library on Google Code. It is designed in java and is used by Google Glass. However, in pursuit of higher efficiency and portability, The Objectivc-c port on C ++ port. Github is actually encapsulated with the OC code and maintenance has been stopped. In this way, the efficiency is very low. We can see that the CPU and memory are soaring under the instrument, and it is easy to crash on machines with small memory.

AVFoundation is optimal in terms of scanning sensitivity and performance.

First import the # import <AVFoundation/AVFoundation. h> framework

 

There are 10 steps to complete the QR code scan:

// 1. obtain the input device AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType: AVMediaTypeVideo]; // 2. create an inPut object NSError * error; AVCaptureDeviceInput * inPut = [[AVCaptureDeviceInput alloc] initWithDevice: device error: & error]; if (inPut = nil) {UIAlertView * aler = [[UIAlertView alloc] initWithTitle: @ "prompt" message: @ "device unavailable" delegate: nil cancelButtonTitle: nil otherButtonTitles: @ "OK", nil]; [self. view AddSubview: aler]; [aler show]; return;} // 3. create an outPut object AVCaptureMetadataOutput * outPut = [[AVCaptureMetadataOutput alloc] init]; // 4. set the outPut stream of the outPut object to be listened to by the proxy (Note: The main thread queue is used for synchronization, and other queues are used for synchronization, which may lead to poor user experience) [outPut setMetadataObjectsDelegate: self queue: dispatch_get_main_queue ()]; // 5. create a session AVCaptureSession * session = [[AVCaptureSession alloc] init]; self. session = session; // 6. add the input and output objects to the session if ([session canAdd Input: inPut]) {[session addInput: inPut];} if ([session canAddOutput: outPut]) {[session addOutput: outPut];} // 7. tell the output object what data needs to be output // prompt: You must set the output of the session to output before specifying the output metadata type! [OutPut setMetadataObjectTypes: @ [AVMetadataObjectTypeQRCode]; // 8. create a preview layer AVCaptureVideoPreviewLayer * preViewLayer = [AVCaptureVideoPreviewLayer layerWithSession: session]; preViewLayer. frame = self. view. bounds; [self. view. layer insertSublayer: preViewLayer atIndex: 0]; // 9. set the scanning range outPut. rectOfInterest = CGRectMake (0.2, 0.18, 0.6, 0.5); // 10. set scan box UIView * boxView = [[UIView alloc] initWithFrame: CGRectMake (0.2 * SrceenW, 0.18 * SrceenH, 0.6 * SrceenW, 0.5 * SrceenH)]; self. boxView = boxView; boxView. layer. borderColor = [UIColor yellowColor]. CGColor; boxView. layer. borderWidth = 3; [self. view addSubview: boxView]; // sets the scanning line CALayer * scanLayer = [[CALayer alloc] init]; self. scanLayer = scanLayer; scanLayer. frame = CGRectMake (0, 0, boxView. bounds. size. width, 2); scanLayer. backgroundColor = [UIColor redColor]. CGColor; [boxView. layer addSublayer: scanLayer]; // starts scanning [session startRunning];

The memory can be optimized in step 1.

@ Property (nonatomic) CGRect rectOfInterest;

This attribute is generally used to tell the system what area it needs to pay attention to. Most app qr code scanning UIS have a box to remind you to place the barcode in that area. The role of this attribute is here, it can set a range to process only the information of the captured image in this range. As a result, the efficiency of our code will be greatly improved when using this attribute. Note:

1. The CGRect parameter is not in the same range as the common Rect parameter. The value ranges from 0 to 1, indicating the proportion.

2. tests show that x corresponds to the vertical distance from the upper left corner, and y corresponds to the horizontal distance from the upper left corner.

3. The width and height settings are similar.

 

----------------------------- The following is the source code:

# Import "ScanQrcodeVController. h"

@ Protocol ScanQrcodeVControllerDelegate <NSObject> // The result returned by the QR code-(void) scanQrcodeWithNString :( NSString *) ruselt; @ end @ interface ScanQrcodeVController: UIViewController @ property) id <ScanQrcodeVControllerDelegate> delegate; @ end

# Import "ScanQrcodeVController. m"

@ Interface ScanQrcodeVController () <AVCaptureMetadataOutputObjectsDelegate> // session @ property (nonatomic, strong) AVCaptureSession * session; // timer @ property (nonatomic, strong) CADisplayLink * link; // Scan Line @ property (nonatomic, strong) CALayer * scanLayer; // scan box @ property (nonatomic, weak) UIView * boxView; // Save the QR code result @ property (nonatomic, copy) NSString * string; @ end @ implementation ScanQrcodeVController-(void) ViewDidLoad {[super viewDidLoad]; self. navigationItem. leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage: [UIImage imageNamed: @ "NavBack"] style: UIBarButtonItemStylePlain target: self action: @ selector (goBack)]; self. navigationItem. rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle: @ "OK" style: UIBarButtonItemStylePlain target: self action: @ selector (doneClick)]; [self scanCode];}-(vo Id) scanCode {CADisplayLink * link = [CADisplayLink displayLinkWithTarget: self selector: @ selector (updataFrame)]; self. link = link; link. frameInterval = 3; [link addToRunLoop: [nsunloop mainRunLoop] forMode: nsunloopcommonmodes]; // 1. obtain the input device AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType: AVMediaTypeVideo]; // 2. create an inPut object NSError * error; AVCaptureDeviceInput * inPut = [AVCaptureDe ViceInput alloc] initWithDevice: device error: & error]; if (inPut = nil) {UIAlertView * aler = [[UIAlertView alloc] initWithTitle: @ "prompt" message: @ "the device is unavailable" delegate: nil cancelButtonTitle: nil otherButtonTitles: @ "OK", nil]; [self. view addSubview: aler]; [aler show]; return;} // 3. create an outPut object AVCaptureMetadataOutput * outPut = [[AVCaptureMetadataOutput alloc] init]; // 4. set the output stream of the agent listening output Object Description: use the main thread queue, the corresponding comparison is synchronized, use other queues, Otherwise, it is easy for users to experience a poor experience [outPut setMetadataObjectsDelegate: self queue: dispatch_get_main_queue ()]; // 5. create a session AVCaptureSession * session = [[AVCaptureSession alloc] init]; self. session = session; // 6. add the inPut and outPut objects to the session if ([session canAddInput: inPut]) {[session addInput: inPut];} if ([session canAddOutput: outPut]) {[session addOutput: outPut];} // 7. tell the output object what data needs to be output // prompt: You must set the output of the session to output first, and then specify the output metadata type.! [OutPut setMetadataObjectTypes: @ [AVMetadataObjectTypeQRCode]; // 8. create a preview layer AVCaptureVideoPreviewLayer * preViewLayer = [AVCaptureVideoPreviewLayer layerWithSession: session]; preViewLayer. frame = self. view. bounds; [self. view. layer insertSublayer: preViewLayer atIndex: 0]; // 9. set the scanning range outPut. rectOfInterest = CGRectMake (0.2, 0.18, 0.6, 0.5); // 10. set scan box UIView * boxView = [[UIView alloc] initWithFrame: CG RectMake (0.2 * SrceenW, 0.18 * SrceenH, 0.6 * SrceenW, 0.5 * SrceenH)]; self. boxView = boxView; boxView. layer. borderColor = [UIColor yellowColor]. CGColor; boxView. layer. borderWidth = 3; [self. view addSubview: boxView]; // sets the scanning line CALayer * scanLayer = [[CALayer alloc] init]; self. scanLayer = scanLayer; scanLayer. frame = CGRectMake (0, 0, boxView. bounds. size. width, 2); scanLayer. backgroundColor = [UICol Or redColor]. CGColor; [boxView. layer addSublayer: scanLayer]; // starts scanning [session startRunning];}-(void) captureOutput :( AVCaptureOutput *) captureOutput failed :( NSArray *) metadataObjects fromConnection :( AVCaptureConnection *) connection {if (metadataObjects. count> 0) {// stop scanning [self. session stopRunning]; // remove the CADisplayLink object [self. link removeFromRunLoop: [nsunloop mainRunLoop] forMode: Nsunloopcommonmodes]; self. link = nil; // retrieve data AVMetadataMachineReadableCodeObject * obj = [metadataObjects lastObject]; self. string = obj. stringValue;} NSLog (@ "scan -- % @", self. string); [NSThread sleepForTimeInterval: 1.0];}-(void) updataFrame {CGRect frame = self. scanLayer. frame; if (self. scanLayer. frame. origin. y> self. boxView. frame. size. height) {frame. origin. y =-20; self. scanLayer. frame = frame ;} Else {frame. origin. y + = 3; self. scanLayer. frame = frame ;}}- (void) viewDidDisappear :( BOOL) animated {[super viewDidDisappear: animated]; // remember to release the CADisplayLink object if (self. link! = Nil) {[self. link invalidate]; self. link = nil ;}/// return the previous interface-(void) goBack {[self. navigationController popViewControllerAnimated: YES];} // QR code scan completed-(void) doneClick {// set proxy if ([self. delegate respondsToSelector: @ selector (scanQrcodeWithNString :)]) {[self. delegate scanQrcodeWithNString: self. string];} [self. navigationController popToRootViewControllerAnimated: YES];} @ end

 

 

 

 

 

 

 

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.