QRコードを読み込む
QRコードの読み込みは下のように行います。
CIDetector
を生成してfeaturesInImage
の引数にCIImageを渡すだけで終わりです。
驚くほど簡単にデータを取得できました。
let imageData = NSData(contentsOfURL: NSURL(string: "QRコードの画像のURL")!) let image = UIImage(data: imageData!)! let ciImage = CIImage(image: image)! let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: nil) let features = detector.featuresInImage(ciImage) for feature in features as! [CIQRCodeFeature] { print(feature.messageString) // これでQRコードの情報を取得できる }
一部端末で起こった問題
一部端末でQRコードを読み込めませんでした。
全く画像を使っても端末によって読めたり読めなかったりします。
デバッグの為にCIContext
をログで出力した所、端末によってはCIContext
がnullになっていました。
デバッグコード・ログは下の通りです。
print(1) // let context = CIContext(CGContext: UIGraphicsGetCurrentContext()!, options: nil) print(2) let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: nil) print(3) NSLog("%@", detector)
うまくいった端末
うまくいかなかった端末
Stack Overflowでも似た現象が投稿されていましたが解決はしていないようです。
ios - Swift : No Matter what I do CIDetector is always nil - Stack Overflow