How to retrieve all data from QR Code Swift 4

无人久伴 提交于 2019-12-06 14:26:04

问题


I have a problem to retrieve and display all the information about the QR Code in Swift 4.

I used a QR Code generator with text extension in which I added

{"number":"+33688888888","amount":"50"}

in my function to call and display information

func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) 
{
    if metadataObjects != nil && metadataObjects.count != 0
    {
        let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject

            if metadataObj.type == AVMetadataObject.ObjectType.qr
            {
                let info = HPPayMoneySuccessModel(titlePage: "Payment", imageInfo: "confirm_checked2", titleDescription: "Congratulations your transaction has been successfully completed", numberString: metadataObj.stringValue!, amountString: metadataObj.stringValue!, buttonTerminate: "OK")

                let segueViewController = HPPayMoneySuccessViewController.init(nibName: "HPPayMoneySuccessViewController", bundle: nil, payMoneySuccessViewModel: info) 

                self.navigationController?.pushViewController(segueViewController, animated: true)

                self.session.stopRunning()
            }
    }  
}

He gets me the information as a string like {"number":"+33688888888","amount":"50"} but I just want +33688888888 in numberString and 50 in amountString

Please help me.


回答1:


You need

guard let stringValue = metadataObj.stringValue else { return }    
if let res = try? JSONSerialization.jsonObject(with:Data(stringValue.utf8), options: []) as? [String:String] ,let fin = res {
    guard let number = fin["number"] , let amount = fin["amount"]  else { return }
    print(number)
    print(amount)
}

OR

if let res = try? JSONDecoder().decode(Root.self, from: Data(stringValue.utf8)) {
    print(res.number)
    print(res.amount) 
}

struct Root : Decodable {
    let number,amount:String
}


来源:https://stackoverflow.com/questions/54221725/how-to-retrieve-all-data-from-qr-code-swift-4

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