Swift: Two-dimensional code scanning and generation using system avfoundation

Source: Internet
Author: User

The system-provided avcapturesession is only suitable for systems above iOS7.0. Please use Zbar to replace the previous

: http://download.csdn.net/detail/huobanbengkui/8881097

To configure project:

Introduced:

Import Foundation
Import Avfoundation

Accept avcapturemetadataoutputobjectsdelegate (such as: Class Qrcodevc:uiviewcontroller, Avcapturemetadataoutputobjectsdelegate, Uialertviewdelegate)

To define a property:

Let device = Avcapturedevice.defaultdevicewithmediatype (Avmediatypevideo)
Let session = Avcapturesession ()
var layer:avcapturevideopreviewlayer?

I. Two-dimensional code scanning

1. Capturing the QR code using the camera

Func Setupcamera () {
Self.session.sessionPreset = Avcapturesessionpresethigh
var error:nserror?
Let input = Avcapturedeviceinput (Device:device, error: &error)
if (Error! = Nil && input = = nil) {
var Erroralert = Uialertview (title: "Reminder", Message: "In the iphone's \" Settings-privacy-camera \ "option, agree to this program to visit your camera", delegate:self, Cancelbuttontitle: "OK")
Erroralert.show ()
Return
}
If Session.canaddinput (input) {
Session.addinput (Input)
}
Layer = Avcapturevideopreviewlayer (session:session)
layer!. Videogravity = Avlayervideogravityresizeaspectfill
Can see the lens area
layer!. frame = CGRectMake (0, 0,320,568)
Self.view.layer.insertSublayer (Self.layer, atindex:0)

Let output = Avcapturemetadataoutput ()
Setting the response area
Output.rectofinterest = CGRectMake (0, 0, 0, 0)
Output.setmetadataobjectsdelegate (self, queue:dispatch_get_main_queue ())
If Session.canaddoutput (output) {
Session.addoutput (Output)
Output.metadataobjecttypes = [Avmetadataobjecttypeqrcode];
}

Session.startrunning ()
}

2. After identifying the QR code, parse the data (implement Avcapturemetadataoutputobjectsdelegate proxy method)

Func captureoutput (captureoutput:avcaptureoutput!, didoutputmetadataobjects metadataobjects: [AnyObject]!, Fromconnection connection:avcaptureconnection!) {

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

If stringvalue! = nil{
Self.session.stopRunning ()


}
}
Self.session.stopRunning ()
var Alertview = Uialertview (title: "QR Code", Message:stringvalue, Delegate:self, cancelbuttontitle: "OK")
Alertview.show ()
}

Finally, when the page disappears:

Override func Viewwilldisappear (Animated:bool) {
Super.viewwilldisappear (animated)

If self.session.running {
Self.session.stopRunning ()
}
}

Two. Two-dimensional code generation

Func createqrforstring (qrstring:string, qrimagename:string?), UIImage? {
If let sureqrstring = qrstring {
Let StringData = sureqrstring.datausingencoding (nsutf8stringencoding, Allowlossyconversion:false)
Create a two-dimensional code filter
Let Qrfilter = Cifilter (name: "Ciqrcodegenerator")
Qrfilter.setvalue (StringData, Forkey: "InputMessage")
Qrfilter.setvalue ("H", Forkey: "Inputcorrectionlevel")
Let Qrciimage = Qrfilter.outputimage
Create a color filter, black and white
Let Colorfilter = Cifilter (name: "Cifalsecolor")
Colorfilter.setdefaults ()
Colorfilter.setvalue (Qrciimage, Forkey: "Inputimage")
Colorfilter.setvalue (Cicolor (red:0, green:0, blue:0), Forkey: "InputColor0")
Colorfilter.setvalue (Cicolor (red:1, Green:1, blue:1), Forkey: "InputColor1")
return QR code image
Let Codeimage = UIImage (CIImage:colorFilter.outputImage.imageByApplyingTransform (Cgaffinetransformmakescale (5, 5)) )
Usually, the QR code is customized, the middle will put the image that wants to express the meaning
If Let Iconimage = UIImage (named:qrimagename!) {
Let rect = CGRectMake (0, 0, codeimage!. Size.width, codeimage!. Size.Height)
Uigraphicsbeginimagecontext (Rect.size)

codeimage!. Drawinrect (Rect)
Let avatarsize = Cgsizemake (Rect.size.width * 0.25, Rect.size.height * 0.25)
Let x = (rect.width-avatarsize.width) * 0.5
Let y = (rect.height-avatarsize.height) * 0.5
Iconimage.drawinrect (CGRectMake (x, Y, Avatarsize.width, avatarsize.height))
Let Resultimage = Uigraphicsgetimagefromcurrentimagecontext ()

Uigraphicsendimagecontext ()
Return Resultimage
}
Return Codeimage
}
return Nil
}

How to use it??

var Imageviewicon = Uiimageview (frame:cgrectmake (100, 100, 150, 150))
Imageviewicon.image = createqrforstring ("Good", Qrimagename: "Ocrback")//"Ocrback" put the name of the middle picture of the QR code
Self.view.addSubview (Imageviewicon)

Last Note:

The Avfoundation framework supports not only QR code scanning. Very many other barcode categories are also supported. Like Code39,code128,aztec, and PDF417. You can try to change it.


Swift: Two-dimensional code scanning and generation using system avfoundation

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.