import UIKit
import AVFoundation
class ScanController:UIViewController,AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate {
let device =AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
let session =AVCaptureSession()
var layer:AVCaptureVideoPreviewLayer?
overridefunc viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor =UIColor.grayColor()
let label_introduction =UILabel(frame:CGRectMake(10,100,300,50))
label_introduction.text ="扫描"
label_introduction.textColor =UIColor.whiteColor()
self.view.addSubview(label_introduction)
setupCamera()
}
func setupCamera(){
self.session.sessionPreset =AVCaptureSessionPresetMedium
do{
let input =try AVCaptureDeviceInput(device:device)
ifsession.canAddInput(input){
session.addInput(input)
}
}catch{
print("崩溃了。。。。。。")
}
layer =AVCaptureVideoPreviewLayer(session: session)
layer?.videoGravity =AVLayerVideoGravityResizeAspectFill
layer?.frame =CGRectMake(20,150, 280,280)
self.view.layer.insertSublayer(self.layer!, atIndex: 0)
let output =AVCaptureMetadataOutput()
output.setMetadataObjectsDelegate(self, queue:dispatch_get_main_queue())
ifsession.canAddOutput(output){
session.addOutput(output)
output.metadataObjectTypes = [AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code]
}
session.startRunning()
}
func captureOutput(captureOutput:AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection:AVCaptureConnection!) {
var stringValue:String?
if metadataObjects.count >0 {
if metadataObjects.first?.type ==AVMetadataObjectTypeQRCode {
stringValue = metadataObjects.first?.stringValue
}elseif metadataObjects.first?.type ==AVMetadataObjectTypeEAN13Code {
stringValue = metadataObjects.first?.stringValue
}else{
stringValue = "再扫啊"
}
}
self.session.stopRunning()
let alertView =UIAlertView()
alertView.message = stringValue
alertView.addButtonWithTitle("Sure")
alertView.delegate =self
alertView.cancelButtonIndex =0
alertView.show()
}
func alertView(alertView:UIAlertView, clickedButtonAtIndex buttonIndex:Int) {
session.startRunning()
}
}