しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

CIDetectorを使ってQRコード読み込んでみる

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)

うまくいった端末

f:id:llcc:20150922162916p:plain

うまくいかなかった端末

f:id:llcc:20150922162914p:plain

Stack Overflowでも似た現象が投稿されていましたが解決はしていないようです。

ios - Swift : No Matter what I do CIDetector is always nil - Stack Overflow