识别图片二维码
点击相册按钮,打开系统相册,CIDetector可以用于人脸识别
@IBAction func photoItem(sender: AnyObject) {
/*
case PhotoLibrary
case Camera
case SavedPhotosAlbum
*/
//1,先查看是否可以打开相册
if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
return
}
//2,创建UIImagePickerController
let imagePiker = UIImagePickerController.init()
//2.1,设置代理
imagePiker.delegate = self
//3,modal
presentViewController(imagePiker, animated: true, completion: nil)
}
实现代理方法
// MARK - UINavigationControllerDelegate, UIImagePickerControllerDelegate代理方法
extension QRBarCodeViewController:UINavigationControllerDelegate, UIImagePickerControllerDelegate{func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
//1,取出选中的图片
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else{
return
}guard let ciImage = CIImage.init(image: image)else{
return
}
//2,从选中的图片中读取二维码数据
//2.1 先创建一个探测器
let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyLow])
//2.2取出探测器得到的数据
let results = detector.featuresInImage(ciImage)
//2.3遍历探测器的数据
for result in results
{
DyLog((result as! CIQRCodeFeature).messageString)
}
//实现了该代理方法,选中了一张图片时系统就不会自动关闭相册控制器
picker.dismissViewControllerAnimated(true, completion: nil)
}
}