Home > Enterprise >  How can I read a value from key (stringValue)?
How can I read a value from key (stringValue)?

Time:10-30

I need help....I only want to print the key value, I don't want to read all the Object

I created a QRCode using this code:

    @IBAction func btnCreate(_ sender: Any) {
        
        if sectionNameTxt.text == "" || sectionExtTxt.text == "" || sectionLocationTxt.text == ""  {
            
        }else{
            let dic = ["sectionName": sectionNameTxt.text!,"sectionExt": sectionExtTxt.text!,"sectionLocation": sectionLocationTxt.text!]
            print("dic:\(dic)")
            
            imgView.image = QRGenerator.generate(from: dic)

            
            
            do {
                let jsonData = try JSONEncoder().encode(dic)
                
                
                if let filter = CIFilter(name: "CIQRCodeGenerator") {
                    filter.setValue(jsonData, forKey: "inputMessage")
                    let transform = CGAffineTransform(scaleX: 10, y: 10)
                    
                    if let output = filter.outputImage?.transformed(by: transform) {
                        imgView.image = UIImage(ciImage: output)
                    }
                    
                }
                
                
            } catch  {
                print(error.localizedDescription)
            }
            
            
        }
        
        
    }

This code is to read the QRCode:

    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        if let metadataObject = metadataObjects.first{
            guard let readleObject = metadataObject as? AVMetadataMachineReadableCodeObject else {return}
            
            AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))

           print((readleObject.stringValue!))

            
            session.stopRunning()

            self.dismiss(animated: true, completion: nil)

        }

output :

{"sectionName":"pharmacy","sectionExt":"1010","sectionLocation":"Main Building - Ground Floor"}

I want read the value of the key1(sectionName) and key2(sectionExt) and key3(sectionLocation) ?

CodePudding user response:

You can use JSONSerialization.

if let data = readleObject.stringValue.data(using: .utf8) {
     if let json = try? JSONSerialization.jsonObject(with: data, options: []), let dataDict = json as? NSDictionary {
          if let sectionName = dataDict["sectionName"] as? String  
          }

     }
}

You can do the rest.

  • Related