iOS development Swift two-dimensional code QRCode read (read from the picture, or scanned through the camera)

Source: Internet
Author: User
Tags uikit

1, directly read the two-dimensional code in the picture

Using Cidetector, you can easily detect and read two-dimensional code. Here's a sample of two-dimensional code from the UIImage, and we're going to print all the two-dimensional code information on the picture.

The code is as follows Copy Code
Import Uikit

Class Viewcontroller:uiviewcontroller {

Override Func Viewdidload () {
Super.viewdidload ()

Let qrcodeimg = UIImage (named: "Codebg.png")
Let Ciimage:ciimage=ciimage (image:qrcodeimg!)!

Let context = Cicontext (Options:nil)
Let Detector:cidetector=cidetector (Oftype:cidetectortypeqrcode,
Context:context, Options: [Cidetectoraccuracy:cidetectoraccuracyhigh])

Let Features=detector.featuresinimage (Ciimage)

Print ("Scan to two-dimensional code number: \ (features.count)")
Traverse all the two-dimensional yards, and box out
For feature in features as! [Ciqrcodefeature] {
Print (feature.messagestring)
}
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}

The console output is as follows:
Scan to two-dimensional code number: 2
Http://www.111cn.net
Http://www.111cn.net
You can see that two two-dimensional codes have been successfully read.

(Note: This I used to use the simulator has not detected a two-dimensional code, the use of real machine debugging is no problem.) Thanks to the netizen "leaves" Reminder, the simulator selected iphone5s and the above equipment can also be detected. )

2, choose the picture from the album to read the two-dimensional code

The code is as follows Copy Code

Import Uikit

Class Viewcontroller:uiviewcontroller, Uiimagepickercontrollerdelegate,
uinavigationcontrollerdelegate {

Override Func Viewdidload () {
Super.viewdidload ()
}

Select album
@IBAction func fromalbum (sender:anyobject) {
Determine if the settings support picture libraries
If Uiimagepickercontroller.issourcetypeavailable (. Photolibrary) {
Initializing the picture controller
Let picker = Uiimagepickercontroller ()
Set up agents
Picker.delegate = Self
Specify picture Controller type
Picker.sourcetype = Uiimagepickercontrollersourcetype.photolibrary
Eject controller, display interface
Self.presentviewcontroller (picker, animated:true, completion: {
()-> Void in
})
}else{
Print ("read album error")
}
}

Select picture after successful agent
Func Imagepickercontroller (Picker:uiimagepickercontroller,
Didfinishpickingmediawithinfo info: [String:anyobject]) {

Get the selected artwork
Let image = Info[uiimagepickercontrolleroriginalimage] as! UIImage

Two-dimensional code reading
Let Ciimage:ciimage=ciimage (image:image)!
Let context = Cicontext (Options:nil)
Let Detector:cidetector=cidetector (Oftype:cidetectortypeqrcode,
Context:context, Options: [Cidetectoraccuracy:cidetectoraccuracyhigh])
Let Features=detector.featuresinimage (Ciimage)
Print ("Scan to two-dimensional code number: \ (features.count)")
Traverse all the two-dimensional yards, and box out
For feature in features as! [Ciqrcodefeature] {
Print (feature.messagestring)
}

Picture Controller exit
Picker.dismissviewcontrolleranimated (True, completion: {
()-> Void in
})
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}

3, using the camera scan to read two-dimensional code
(1) The main use of scanning is avfoundation, easy to use
(2) The probe detection area can be set up through the Avcapturemetadataoutput Rectofinterest property. Add a box to the probe area and only the two-dimensional code in the box is scanned.

The effect chart is as follows:


The code is as follows

The code is as follows Copy Code

Import Uikit
Import Avfoundation

Class Viewcontroller:uiviewcontroller, Avcapturemetadataoutputobjectsdelegate,
uialertviewdelegate{

var scanrectview:uiview!
var device:avcapturedevice!
var input:avcapturedeviceinput!
var output:avcapturemetadataoutput!
var session:avcapturesession!
var preview:avcapturevideopreviewlayer!

Override Func Viewdidload () {
Super.viewdidload ()
}

Scanning through the camera
@IBAction func Fromcamera (sender:anyobject) {
do{
Self.device = Avcapturedevice.defaultdevicewithmediatype (Avmediatypevideo)

Self.input = Try Avcapturedeviceinput (device:device)

Self.output = Avcapturemetadataoutput ()
Output.setmetadataobjectsdelegate (self, queue:dispatch_get_main_queue ())

Self.session = Avcapturesession ()
If Uiscreen.mainscreen (). bounds.size.height<500 {
Self.session.sessionPreset = avcapturesessionpreset640x480
}else{
Self.session.sessionPreset = Avcapturesessionpresethigh
}

Self.session.addInput (Self.input)
Self.session.addOutput (Self.output)

Self.output.metadataObjectTypes = [Avmetadataobjecttypeqrcode]

To compute the intermediate detectable region
Let windowsize:cgsize = Uiscreen.mainscreen (). bounds.size;
Let scansize:cgsize = Cgsizemake (WINDOWSIZE.WIDTH*3/4,
WINDOWSIZE.WIDTH*3/4);
var scanrect:cgrect = CGRectMake (windowsize.width-scansize.width)/2,
(windowsize.height-scansize.height)/2, scansize.width, scansize.height);
Compute rectofinterest Note x,y swap position
Scanrect = CGRectMake (Scanrect.origin.y/windowsize.height,
Scanrect.origin.x/windowsize.width,
Scanrect.size.height/windowsize.height,
Scanrect.size.width/windowsize.width);
To set up a detectable area
Self.output.rectOfInterest = Scanrect

Self.preview = Avcapturevideopreviewlayer (session:self.session)
Self.preview.videoGravity = Avlayervideogravityresizeaspectfill
Self.preview.frame = Uiscreen.mainscreen (). Bounds
Self.view.layer.insertSublayer (Self.preview, atindex:0)

Add the middle Probe area Green box
Self.scanrectview = UIView ();
Self.view.addSubview (Self.scanrectview)
Self.scanRectView.frame = CGRectMake (0, 0, scansize.width, scansize.height);
Self.scanRectView.center = Cgpointmake (
Cgrectgetmidx (Uiscreen.mainscreen (). Bounds),
Cgrectgetmidy (Uiscreen.mainscreen (). bounds));
Self.scanRectView.layer.borderColor = Uicolor.greencolor (). Cgcolor
Self.scanRectView.layer.borderWidth = 1;

Start capturing
Self.session.startRunning ()
}catch _ as Nserror{
Print error messages
Let Erroralert = Uialertview (title: "Reminder",
Message: "Please allow this program to access your camera on the iphone's settings-privacy-camera \" option,
Delegate:self,
Cancelbuttontitle: "OK")
Erroralert.show ()
}
}

Camera capture
Func Captureoutput (captureoutput:avcaptureoutput!,
Didoutputmetadataobjects metadataobjects: [anyobject]!,
Fromconnection connection:avcaptureconnection!) {

var stringvalue:string?
If Metadataobjects.count > 0 {
Let MetadataObject = Metadataobjects[0] as! Avmetadatamachinereadablecodeobject
StringValue = Metadataobject.stringvalue

If StringValue!= nil{
Self.session.stopRunning ()
}
}
Self.session.stopRunning ()
Output results
Let Alertview = Uialertview (title: "Two-dimensional Code", Message:stringvalue,
Delegate:self, Cancelbuttontitle: "OK")
Alertview.show ()
}

message box disappears after confirmation
Func Alertview (Alertview:uialertview, Willdismisswithbuttonindex buttonindex:int) {
Continue scanning
Self.session.startRunning ()
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}

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.