我正在进行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