First step: Join the framework Avfoundation.framework
Directory selection targets, Build phases, Link Binary with Libraries, add avfoundation.framework to
Step Two: Add the following code, and add the Protocol avcapturemetadataoutputobjectsdelegate,
Defining Global Variables
var session:avcapturesession? ; var previewlayer:avcapturevideopreviewlayer?;
Use the Readqrcode () function where you need it
func Readqrcode () {//1. Get the camera devicevar device:avcapturedevice =Avcapturedevice.defaultdevicewithmediatype (Avmediatypevideo); //2. Setting the inputvar error:nserror?; var input:avcapturedeviceinput= Avcapturedeviceinput.deviceinputwithdevice (device, error: &error) asAvcapturedeviceinput; if(Error! =Nil) {println ("no webcam \ (error?. Localizeddescription)"); return; } //3. Set output (metadata metadata)var output:avcapturemetadataoutput =Avcapturemetadataoutput (); //3.1 Setting the proxy for the output//Description: Use the main thread queue, the corresponding synchronization, use other queues, the corresponding different steps, easy to let users have a bad experienceoutput.setmetadataobjectsdelegate (Self, Queue:dispatch_get_main_queue ()); //4. Shooting Sessionsvar session1:avcapturesession =avcapturesession (); Session1.addinput (input); Session1.addoutput (output); //4.1 Setting the format of the output//tip: Be sure to specify the output metadata type after you set the output of the session to output! Output.metadataobjecttypes =[Avmetadataobjecttypeqrcode]; //5. Set the preview layer (to allow the user to see the scanning situation)var preview:avcapturevideopreviewlayer = avcapturevideopreviewlayer.layerwithsession (Session1) asAvcapturevideopreviewlayer; //5.1 Setting the properties of the preview layerPreview.videogravity =Avlayervideogravityresizeaspectfill; //5.2 Setting the size of the preview layerPreview.frame =Self.view.bounds; //5.3 Adding layers to a view's layerSelf.view.layer.insertSublayer (preview, Atindex:0); Self.previewlayer=Preview; //6. Start the sessionsession1.startrunning (); Self.session=Session1; } func captureoutput (Captureoutput:avcaptureoutput!, didoutputmetadataobjects metadataobjects: [anyobject]!, Fromconnection connection:avcaptureconnection!) { //frequent scans, invoking proxy methods//1. If the scan is complete, stop the sessionSelf.session?. stoprunning (); //2. Delete the preview layerSelf.previewlayer?. Removefromsuperlayer (); println (metadataobjects); //3. Setting the interface to display the scan results if(Metadataobjects.count >0) {var obj:avmetadatamachinereadablecodeobject= metadataobjects[0] asAvmetadatamachinereadablecodeobject; //tip: If you need to scan for information such as URLs or business cards, you can expand here! println"The results are as follows:"+obj.stringvalue); } }
iOS controls-Swift integrated iOS with API scan QR code