1. 程式人生 > >Swift CIDetector識別相冊的二維碼

Swift CIDetector識別相冊的二維碼

rar ace iss delegate text ava true col navi

import UIKit

class firstViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

var picker :UIImagePickerController!

@IBAction func button(_ sender: UIButton) {

if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){

picker = UIImagePickerController()

picker.delegate = self

picker.sourceType = .photoLibrary

self.present(picker, animated: true, completion: nil)

}

}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

//獲取選擇的圖片

let image = info[UIImagePickerControllerOriginalImage] as! UIImage

//二維碼讀取

DispatchQueue.global().async {

let imageData = UIImagePNGRepresentation(image)

let ciImage:CIImage=CIImage(data: imageData!)!

let detector = CIDetector(ofType: CIDetectorTypeQRCode, context:nil,options:[CIDetectorAccuracy:CIDetectorAccuracyHigh])

let feature = detector?.features(in: ciImage)

let f = feature?.first as! CIQRCodeFeature

print(f.messageString ?? "")

}

//返回

picker.dismiss(animated: true, completion: {

() -> Void in

})

}

}

Swift CIDetector識別相冊的二維碼