扫描QR码时,我的视图消失了

时间:2017-12-28 22:34:29

标签: ios swift swift4

我第一次使用AVFoundation,我的脚本工作有点......

我正在制作一个票务应用程序,女巫正在扫描票证上的二维码并检查数据库是否使用过。 (我隐藏了我的API登录信息)。但是一旦我扫描了qr代码,我的代码就会运行,我在控制台中获得了一张票有效的plottet,但是viewcontroller消失了,然后返回我的登录页面。

我正在使用此代码,我的登录页面显示带有QR码的viewcontroller。

let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "scanner") as UIViewController

self.present(viewController, animated: false, completion: nil)

带有QR扫描仪的viewcontroller。

//
//  scanner.swift
//  GB Billet Scanner
//
//  Created by Benjamin Eibye on 26/12/2017.
//  Copyright © 2017 GymBilletter.dk. All rights reserved.
//

import UIKit
import AVFoundation
import Alamofire

class scanner: UIViewController, AVCaptureMetadataOutputObjectsDelegate {

    @IBOutlet weak var videoPreview: UIView!
    @IBOutlet weak var navnLabel: UILabel!
    let avCaptureSession = AVCaptureSession()

    var returnValue: String = String()

    enum error: Error {
        case noCameraAvailable
        case videoInputInitFail
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Creating session

        do {
            try scanQRCode()
        } catch {
            print("Failed to scan the QR/BarCode")
        }

    }

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

    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        avCaptureSession.stopRunning()

        if let metadataObject = metadataObjects.first {
            let readableObject = metadataObject as! AVMetadataMachineReadableCodeObject;

            AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
            //print(readableObject.stringValue!);

            navnLabel.text = "Indlæser billet #\(readableObject.stringValue!)"

            let urlEnc = "https://domain?token=\(String(describing: UserDefaults.standard.object(forKey: "token")!))&ticket=\(readableObject.stringValue!)"

            Alamofire.request(urlEnc).responseJSON { response in
                //print(urlEnc)
                //debugPrint(response)
                //print(response.result)
                if let result = response.result.value {
                    let JSON = result as! NSDictionary

                    if JSON["error"] as? Int == 5002 {
                        print("User not Authendicated")
                        print(urlEnc)
                        self.navnLabel.text = "Telefonen er ikke logget ind"
                        self.avCaptureSession.startRunning()

                    } else if JSON["error"] as? Int == 5003 {
                        print("Ticket not Found")
                        self.navnLabel.text = "Billetten blev ikke fundet"
                        self.avCaptureSession.startRunning()

                    } else {
                        // Billetten eksistere
                        print("Billet fundet")
                        if JSON["active"] as! String == "1" {

                            print("ticket Valid")
                            self.avCaptureSession.startRunning()

                        } else {
                            print("Billetten er blevet brugt")
                            self.navnLabel.text = "Billetten er blevet brugt \(String(describing: JSON["used_date"]))"
                        }

                    }

                }

            }


        }

        dismiss(animated: true)
    }

    func scanQRCode() throws {

        guard let avCaptureDevice = AVCaptureDevice.default(for: AVMediaType.video) else {
            print("no camera.")
            throw error.noCameraAvailable
        }

        guard let avCaptureInput = try? AVCaptureDeviceInput(device: avCaptureDevice) else {
            print("Faild to init camera.")
            throw error.videoInputInitFail
        }

        let avCaptureMetadataOutput = AVCaptureMetadataOutput()
        avCaptureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        avCaptureSession.addInput(avCaptureInput)
        avCaptureSession.addOutput(avCaptureMetadataOutput)

        avCaptureMetadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]

        let avCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: avCaptureSession)
        avCaptureVideoPreviewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
        avCaptureVideoPreviewLayer.frame = videoPreview.bounds

        self.videoPreview.layer.addSublayer(avCaptureVideoPreviewLayer)

        avCaptureSession.startRunning()


    }

    @IBAction func anuller(_ sender: Any) {

        navnLabel.text = "Scan billet."
        avCaptureSession.startRunning()

    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

1 个答案:

答案 0 :(得分:2)

无论返回什么内容,都会调用dismiss(animated: true)函数末尾的metadataOutput(...)