- 二維碼讀取包括:
- 直接對靜態(tài)的圖片進行二維碼識別,最低支持iOS8.0
- 利用攝像頭掃描識別(動態(tài)圖片),需要真機設備
讀取圖片二維碼 <- swift
-
導入框架(可選)
import CoreImage -
實現(xiàn)代碼
@IBOutlet weak var qrCodeImage: UIImageView! override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { // 0. 創(chuàng)建一個上下文 let context = CIContext() // 1. 創(chuàng)建一個二維碼探測器 let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: context, options: [CIDetectorAccuracy : CIDetectorAccuracyHigh]) // 2. 探測二維碼圖片的特征 guard let image = qrCodeImage.image else { return } let imageCI = CIImage(image: image) let features = detector.featuresInImage(imageCI!) // 3. 處理識別到的特征值 for feature in features { if feature.isKindOfClass(CIQRCodeFeature) { let qrCodeFeature = feature as! CIQRCodeFeature print(qrCodeFeature.messageString) // 繪制識別到的二維碼圖片,詳見“5.識別二維碼- 描繪邊框” } } // 將重新繪制的圖片顯示(可選),沒繪制可以不設置 // qrCodeImage.image = tempImage // 4. 彈框顯示內(nèi)容 // 4.1 創(chuàng)建彈框控制器 let alterVC = UIAlertController(title: "結(jié)果", message: resultStrs.description, preferredStyle: UIAlertControllerStyle.Alert) // 4.2 給控制器設置行為 let action = UIAlertAction(title: "關閉", style: UIAlertActionStyle.Default) { (action: UIAlertAction) in self.dismissViewControllerAnimated(true, completion: nil) } // 4.3 添加行為 alterVC.addAction(action) // 4.4 彈出提示內(nèi)容 presentViewController(alterVC, animated: true, completion: nil) }