Every step: Add Avfoundation.framework Library
General > Linked Frameworks and Libraries
Step Two: Code integration
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
1. There's a material.
@interface Viewcontroller () <AVCaptureMetadataOutputObjectsDelegate>
/** 2. Input settings capture the information captured by the camera */
@property (nonatomic, strong) Avcapturedeviceinput *input;
/** 3. Output device parsing the information collected by the input device */
@property (nonatomic, strong) Avcapturemetadataoutput *output;
/** 4. Layer (the special layer can show the image captured by the camera) shows the information collected by the input device * *
@property (nonatomic, strong) Avcapturevideopreviewlayer *layer;
/** 5. Associating input devices and output device sessions */
@property (nonatomic, strong) avcapturesession *session;
@end
@implementation Viewcontroller
-(void) Viewdidload {
[Super Viewdidload];
}
Click Scan QR Code
-(Ibaction) Click: (ID) Sender {
1. Create an input device
Avmediatypevideo camera
Avmediatypeaudio microphone
Avcapturedeviceinput input Device Default back
Avcapturedevice *device = [Avcapturedevice defaultdevicewithmediatype:avmediatypevideo];
Nsarray *alldevice = [Avcapturedevice deviceswithmediatype:avmediatypevideo];
Self.input = [Avcapturedeviceinput deviceinputwithdevice:[alldevice firstobject] error:nil];
2. Creating an output device
Self.output = [[Avcapturemetadataoutput alloc]init];
Parse the returned data
Set the proxy for the output device to return the parsed data
[Self.output setmetadataobjectsdelegate:self Queue:dispatch_get_main_queue ()];
3. Create a session
Self.session = [[Avcapturesession alloc]init];
4. Associating sessions and devices
if ([Self.session canAddInput:self.input]) {
[Self.session AddInput:self.input];
}
if ([Self.session canAddOutput:self.output]) {
[Self.session AddOutput:self.output];
}
Tell the data type Avmetadataobjecttypeqrcode two-dimensional code
Self.output.metadataObjectTypes = @[avmetadataobjecttypeqrcode];
Scan box Size entire screen
[Self.session setsessionpreset:avcapturesessionpreset640x480];
5. Assign a frame to the layer and add it to the view
Self.layer = [[Avcapturevideopreviewlayer alloc]initwithsession:self.session];
Self.layer.frame = Self.view.bounds;
[Self.view.layer AddSublayer:self.layer];
Open session
[Self.session startrunning];
}
The method that will be called when the result is scanned
-(void) Captureoutput: (Avcaptureoutput *) captureoutput didoutputmetadataobjects: (Nsarray *) metadataobjects Fromconnection: (avcaptureconnection *) connection{
Avmetadatamachinereadablecodeobject *OBJC = [Metadataobjects firstobject];
NSString *str = Objc.stringvalue;
NSLog (@ "%@", str);
Stop scanning
[Self.session stoprunning];
Remove Layer
[Self.layer Removefromsuperlayer];
}
@end
iOS QR code scan