How to scan Qr code from an image picked with UIImagePickerController in iOS

风格不统一 提交于 2019-12-04 09:41:56

I know you might have found solution for this but i am replying to the post if my answer may help other for relevant question.

Here I am posting my code to ScanQRCode from image picked from gallery without using any Library.

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



    if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
                 let detector:CIDetector=CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])

    let ciImage:CIImage = CIImage(image:pickedImage)!

    var qrCodeLink = ""

    let features=detector.featuresInImage(ciImage)

    for feature in features as! [CIQRCodeFeature] {

        qrCodeLink += feature.messageString
    }

    print(qrCodeLink)//Your result from QR Code
}

    dismissViewControllerAnimated(true, completion: nil)
}

Updated to swift 5 and more "swifty" way based on @Dev_Tandel response.
But for me .originalImage worked instead of .editedImage.

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

    guard let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage,
        let detector = CIDetector(ofType: CIDetectorTypeQRCode,
                                  context: nil,
                                  options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]),
        let ciImage = CIImage(image: pickedImage),
        let features = detector.features(in: ciImage) as? [CIQRCodeFeature] else { return }

    let qrCodeLink = features.reduce("") { $0 + ($1.messageString ?? "") }

    print(qrCodeLink)//Your result from QR Code
}

In Apple's iOS, a QR code reader is not natively included. Therefore there is no API from Apple you can use.

You have to rely either or third party SDKs or write your own code.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!