iOS7 native Sweep code

Source: Internet
Author: User

Many applications have the ability to scan the QR code, in the development of these features may be exposed to ZXing or zbar such a third-party scanning library, but starting from IOS 7 system native API support by scanning to obtain QR code functions. Today, we'll talk about the native sweep code.

0. Camera Permissions

Also starting with IOS 7, the app wants to use the camera feature first to get the user's authorization, so first determine the authorization situation.

    • Method of Judging Authorization:
AVAuthorizationStatus authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];  
    • The avauthorizationstatus enum values are:
typedef NS_ENUM(NSInteger, AVAuthorizationStatus) {    AVAuthorizationStatusNotDetermined = 0,  AVAuthorizationStatusRestricted, // 受限,有可能开启了访问限制 AVAuthorizationStatusDenied, AVAuthorizationStatusAuthorized} NS_AVAILABLE_IOS(7_0);
    • Request Authorization Method:
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler: ^(BOOL granted) {    if (granted) {         [self startCapture]; // 获得授权    } else {            NSLog(@"%@", @"访问受限"); }}];
    • Full Authorization processing logic:
Avauthorizationstatus authorizationstatus = [Avcapturedevice authorizationstatusformediatype:avmediatypevideo];Switch (authorizationstatus) {  Case avauthorizationstatusnotdetermined: {  [Avcapturedevice requestaccessformediatype:avmediatypevideo Completionhandler: ^ (BOOL granted) {   if (granted) {   [Self startcapture];  }else {   NSLog (@"%@",@ "Access restricted");  } }];  Break} case avauthorizationstatusauthorized: { [self startcapture];  Break  ; } Case  avauthorizationstatusrestricted: Case avauthorizationstatusdenied: { NSLog (@ "%@", @ "Access restricted"); Break   ; }  default: {break  ; }}           
1. Sweep code
    • Avcapturesession

The sweep code is a process from the camera (input) to parsing out the string (output), which is coordinated with avcapturesession. It uses avcaptureconnection to connect individual input and output, and it can also be used to control the flow of data for input and output. Their relationship is as follows:

    • The code of the sweep code is very simple, as follows:
Avcapturesession*session = [[Avcapturesession alloc] init]; Avcapturedevice*device = [Avcapturedevice defaultdevicewithmediatype:avmediatypevideo]; Nserror*error; Avcapturedeviceinput*deviceinput = [Avcapturedeviceinput deviceinputwithdevice:device error:&error];if (deviceinput) {[Session Addinput:deviceinput];Avcapturemetadataoutput*metadataoutput = [[Avcapturemetadataoutput alloc] init];[Metadataoutput setmetadataobjectsdelegate:self Queue:dispatch_get_main_queue ()];[Session Addoutput:metadataoutput]; //This line of code to be set metadataobjecttypes before metadataoutput.metadataobjecttypes = @[avmetadataobjecttypeqrcode];  Avcapturevideopreviewlayer *previewlayer = [[Avcapturevideopreviewlayer alloc] initwithsession:session];  previewlayer.videogravity = Avlayervideogravityresizeaspectfill; previewlayer.frame = self.view.frame; [Self.view.layer insertsublayer:previewlayer Atindex:0];  [Session startrunning];} else { NSLog (@ "%@", error);}            
    • The sweep code results are returned from the delegate method:
*)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {  AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects.firstObject; if ([metadataObject.type isEqualToString:AVMetadataObjectTypeQRCode] && !self.isQRCodeCaptured) { // 成功后系统不会停止扫描,可以用一个变量来控制。  self.isQRCodeCaptured = YES;  NSLog(@"%@", metadataObject.stringValue); }}
2, from the image file analysis (IOS 8)

Starting with IOS 8 You can also parse the QR code from the image file and use the cidetector of the Core image.

The code is also simple:

*detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy:CIDetectorAccuracyHigh }];  CIImage *image = [[CIImage alloc] initWithImage:[UIImage imageNamed:@"foobar.png"]];  NSArray *features = [detector featuresInImage:image]; for (CIQRCodeFeature *feature in features) { NSLog(@"%@", feature.messageString);}

(foobar.png)

3. Generate two-dimensional code images

The generation of two-dimensional code used to ciqrcodegenerator this cifilter. It has two fields that can be set, InputMessage and Inputcorrectionlevel. InputMessage is a NSData object, which can be a string or a URL. Inputcorrectionlevel is a single-letter (@ "L", @ "M", @ "Q", one in @ "H"), representing different levels of fault tolerance, by default @ "M".

QR code is fault-tolerant, QR code graphics if damaged, can still be read by the machine, up to 7%~30% area damage can still be read. Therefore, the QR code can be widely used in the transport of the outer box.

Relatively, the higher the fault tolerance rate, the larger the QR Code graphics area. So the general tradeoff is to use 15% fault-tolerant capabilities.

Error correction capacity L level 7% Loadline can be corrected

Loadline of M level 15% can be corrected

Q-level 25% loadline can be corrected

H-level 30% Loadline can be modified

So many of the two-dimensional code in the middle of the picture and so on, but still can be identified is the reason.

The code is as follows, and it should be noted that:

    • 1) The official proposal uses the nsisolatin1stringencoding to encode, but after testing this kind of code to the Chinese or the expression cannot generate, changes the nsutf8stringencoding to be possible.
    • 2) The resulting picture size (outputImage.extent.size) is smaller and needs to be scaled.
    • 3) The generated ciimage need to be converted to cgimage before they can be saved, because Uiimagepngrepresentation accepts the UIImage to have cgimage, if not, or the bitmap format will return nil.
return image as PNG. May return nil if image has no CGImageRef or invalid bitmap formatNSData * UIImagePNGRepresentation(UIImage *image); 
NSString*urlstring =@ "http:weibo.com/u/2255024877"; NSData*data = [URLString datausingencoding:nsisolatin1stringencoding]; Nsisolatin1stringencoding encoding Cifilter*filter = [Cifilter filterwithname:@ "Ciqrcodegenerator"]; [Filter Setvalue:data Forkey:@ "InputMessage"]; Ciimage *outputimage = filter.outputimage; NSLog (@ "%@", Nsstringfromcgsize (outputImage.extent.size)); Cgaffinetransform transform = cgaffinetransformmakescale (scale, scale); //scale is magnification ciimage *transformimage = [Outputimage imagebyapplyingtransform:transform];  Save Cicontext *context = [Cicontext Contextwithoptions:nil]; Cgimageref imageref = [context createcgimage:transformimage fromRect:transformImage.extent]; UIImage *qrcodeimage = [UIImage imagewithcgimage:imageref]; [Uiimagepngrepresentation (Qrcodeimage) Writetofile:path Atomically:no]; Cgimagerelease (IMAGEREF); 

(generated two-dimensional code picture)

4. Scan Box
    • Rectofinterest

Scanning the Previewlayer Scan range is the entire visual range, but some requirements may need to specify the area to scan, although I think this is not necessary, because the whole screen can be swept and why to specify a box? But if you really need to do this, you can set the Metadataoutput rectofinterest.

It is important to note that:

    • 1) The value of Rectofinterest is quite special and needs to be transformed. Its default value is (0.0, 0.0, 1.0, 1.0).
metadataOutput.rectOfInterest = [previewLayer metadataOutputRectOfInterestForRect:CGRectMake(80, 80, 160, 160)]; // 假设扫码框的 Rect 是 (80, 80, 160, 160) 
    • 2) Rectofinterest can not be set directly in the setting metadataoutput, but need in this avcaptureinputportformatdescriptiondidchangenotification The notification is set, otherwise metadataoutputrectofinterestforrect: The conversion method returns (0, 0, 0, 0).
[[NSNotificationCenter defaultCenter] addObserverForName:AVCaptureInputPortFormatDescriptionDidChangeNotification                                                        object:nil                                                         queue:[NSOperationQueue currentQueue]                                                    usingBlock: ^(NSNotification *_Nonnull note) {      metadataOutput.rectOfInterest = [previewLayer metadataOutputRectOfInterestForRect:CGRectMake(80, 80, 160, 160)];}];
    • The appearance of the Sweep code box

The Sweep code box is generally translucent black, and it has no color inside.

(Sweep code box)

You can add views around the sweep code box, but the easier way is to customize a view in the DrawRect: Draw the path of the Sweep code box. The code is as follows:

 Cgcontextref CTX = Uigraphicsgetcurrentcontext (); CGFloat width = cgrectgetwidth ([UIScreen mainscreen].bounds); [[[Uicolor Blackcolor] Colorwithalphacomponent:0.5] setfill]; Cgmutablepathref Screenpath = cgpathcreatemutable (); Cgpathaddrect (Screenpath, null, self.bounds); Cgmutablepathref Scanpath = cgpathcreatemutable (); Cgpathaddrect (Scanpath, null, CGRectMake (80, 80, Span class= "number" >160, 160); Cgmutablepathref path = cgpathcreatemutable (); Cgpathaddpath (Path, null, screenpath); Cgpathaddpath (Path, null, scanpath); Cgcontextaddpath (CTX, path); Cgcontextdrawpath (CTX, Kcgpatheofill); //kcgpatheofill mode Cgpathrelease (Screenpath); Cgpathrelease (Scanpath); Cgpathrelease (path); 

iOS7 native Scan code

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.