Tester
Tester

Reputation: 685

How to retrieve data from VCard using swift

I'm working on QR code scanning. Using the following swift code, the data in the QR code is getting printed in the console.

import UIKit
import AVFoundation

class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate
{
    let session = AVCaptureSession()
    @IBOutlet weak var square: UIImageView!
    var video = AVCaptureVideoPreviewLayer()

    override func viewDidLoad()
    {

        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


    }

    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {

        if metadataObjects != nil && metadataObjects.count != 0
        {
            if let object = metadataObjects[0] as? AVMetadataMachineReadableCodeObject
            {
                if object.type == AVMetadataObjectTypeQRCode
                {
                    print(object.stringValue)

                    let alert = UIAlertController(title: "QR Code", message: object.stringValue, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "Okey", style: .default, handler: nil))
                   /* alert.addAction(UIAlertAction(title: "Copy", style: .default, handler: { (nil) in
                        UIPasteboard.general.string = object.stringValue
                    }))
                */
                    present(alert, animated: true, completion: nil)

                    if metadataObjects.count > 0
                    {
                        print("-------------------------------------------------")
                        self.session.stopRunning()

                    }

                }
            }
        }
    }

    @IBAction func startButton(_ sender: Any)
    {
        // Creating session
       // let session = AVCaptureSession()

        // Define capture device
        let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

        do {
            let input = try AVCaptureDeviceInput(device: captureDevice)
            session.addInput(input)
        } catch {
            print("Error")
        }

        let output = AVCaptureMetadataOutput()
        session.addOutput(output)

        output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)

        output.metadataObjectTypes = [AVMetadataObjectTypeQRCode]

        video = AVCaptureVideoPreviewLayer(session: session)
        video.frame = view.layer.bounds
        view.layer.addSublayer(video)
        self.view.bringSubview(toFront: square)
        session.startRunning()        
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

OUTPUT:

BEGIN:VCARD
VERSION:2.1
FN:John Peter
N:Peter;John
TITLE:Admin
TEL;CELL:+91 431 524 2345
TEL;WORK;VOICE:+91 436 542 8374
EMAIL;WORK;INTERNET:[email protected]
URL:www.facebook.com
ADR;WORK:;;423 ofce sales Center;Newark;DE;3243;USA
ORG:xxx Private limited
END:VCARD

Now what I want is, how to retrieve the data in the VCard format specifically, like getting first name, last name, email id, mobile number, etc. A similar question to this is asked before, but it was in objective-c. I don't know how to do this swift 3. Thanks in advance.

Upvotes: 3

Views: 5295

Answers (2)

Sumit singh
Sumit singh

Reputation: 2446

Here you can check Updated answer for swift 4 of Mateusz Szlosek

 var str = "BEGIN:VCARD \n" +
  "VERSION:2.1 \n" +
  "FN:John Peter \n" +
  "N:Peter;John \n" +
  "TITLE:Admin \n" +
  "TEL;CELL:+91 431 524 2345 \n" +
  "TEL;WORK;VOICE:+91 436 542 8374 \n" +
  "EMAIL;WORK;INTERNET:[email protected] \n" +
  "URL:www.facebook.com \n" +
  "ADR;WORK:;;423 ofce sales Center;Newark;DE;3243;USA \n" +
  "ORG:xxx Private limited \n" +
"END:VCARD"

func fectchContact(){
  if let data = str.data(using: .utf8) {
    do{
      let contacts = try CNContactVCardSerialization.contacts(with: data)
      let contact = contacts.first
      print("\(String(describing: contact?.familyName))")
    }
    catch{
      // Error Handling
      print(error.localizedDescription)
    }
  }
}

Upvotes: 0

Mateusz Szlosek
Mateusz Szlosek

Reputation: 1225

Here's a sample code from Playground I used. It's not the best, but You'll get the idea:

import UIKit
import Contacts

var str = "BEGIN:VCARD \n" +
"VERSION:2.1 \n" +
"FN:John Peter \n" +
"N:Peter;John \n" +
"TITLE:Admin \n" +
"TEL;CELL:+91 431 524 2345 \n" +
"TEL;WORK;VOICE:+91 436 542 8374 \n" +
"EMAIL;WORK;INTERNET:[email protected] \n" +
"URL:www.facebook.com \n" +
"ADR;WORK:;;423 ofce sales Center;Newark;DE;3243;USA \n" +
"ORG:xxx Private limited \n" +
"END:VCARD"

if let data = str.data(using: .utf8) {
    let contacts = try CNContactVCardSerialization.contacts(with: data)
    let contact = contacts.first
    print("\(String(describing: contact?.familyName))")
}

The output from CNContactVCardSerialization.contacts(with: data) is an array of CNContact (reference).

Upvotes: 15

Related Questions