我正在進行QR碼掃描。使用以下swift代碼,QR代碼中的數據將被打印到控制檯中。如何使用swift從VCard檢索數據
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
現在,我要的是,如何具體檢索vCard格式的數據,喜歡把自己的名字,姓氏,電子郵件ID,手機號碼等。以前有人問過類似的問題,但它是在Objective-C中。我不知道如何做到這一點3.預先感謝。
看看[CNContactVCardSerialization(https://developer.apple.com/documentation/contacts/cncontactvcardserialization)(MacOS的10.11+ ,iOS 9+) – vadian
檢查了它,但找不到相關解決方案。 – Tester
該類中只有兩個方法(除了'descriptorForRequiredKeys'),一個用於編碼解碼。這就像'JSONSerialization',但要簡單得多。 – vadian