1 包含
#import <AVFoundation/AVFoundation.h>
2 导入AVFoundation库文件
1 #import "ViewController.h" 2 #import <AVFoundation/AVFoundation.h> 3 @interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate> 4 - (IBAction)scan:(UIButton *)sender; 5 @property (strong,nonatomic)AVCaptureDevice *device; 6 @property (strong,nonatomic)AVCaptureDeviceInput *input; 7 @property (strong,nonatomic)AVCaptureMetadataOutput *output; 8 @property (strong,nonatomic)AVCaptureSession *session; 9 @property (strong,nonatomic)AVCaptureVideoPreviewLayer *preview; 10 @end 11 12 @implementation ViewController 13 14 - (void)viewDidLoad { 15 [super viewDidLoad]; 16 // Do any additional setup after loading the view, typically from a nib. 17 18 } 19 20 - (void)setupCamera 21 { 22 // Device 23 _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; 24 25 // Input 26 _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil]; 27 28 // Output 29 _output = [[AVCaptureMetadataOutput alloc]init]; 30 [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()]; 31 32 // Session 33 _session = [[AVCaptureSession alloc]init]; 34 [_session setSessionPreset:AVCaptureSessionPresetHigh]; 35 if ([_session canAddInput:self.input]) 36 { 37 [_session addInput:self.input]; 38 } 39 40 if ([_session canAddOutput:self.output]) 41 { 42 [_session addOutput:self.output]; 43 } 44 45 // 条码类型 AVMetadataObjectTypeQRCode 46 _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode]; 47 48 // Preview 49 _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session]; 50 _preview.videoGravity = AVLayerVideoGravityResizeAspectFill; 51 _preview.frame =CGRectMake(20,110,280,280); 52 [self.view.layer insertSublayer:self.preview atIndex:0]; 53 54 55 56 // Start 57 [_session startRunning]; 58 } 59 #pragma mark AVCaptureMetadataOutputObjectsDelegate 60 - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection 61 { 62 NSString *stringValue = [[NSString alloc] init]; 63 64 if (metadataObjects.count >0) { 65 AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects objectAtIndex:0]; 66 stringValue = metadataObject.stringValue; 67 } 68 69 [_session stopRunning]; 70 NSLog(@"%@",stringValue); 71 [self dismissViewControllerAnimated:YES completion:^{ 72 UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil 73 message:stringValue 74 delegate:nil 75 cancelButtonTitle:@"OK" 76 otherButtonTitles:nil,nil]; 77 [alert show]; 78 }]; 79 } 80 - (IBAction)scan:(UIButton *)sender { 81 [self setupCamera]; 82 }
有待完善。。。。。