当前位置: 首页 > 知识库问答 >
问题:

我无法将值传递给下一个ViewController

嵇星海
2023-03-14

我正在工作的这个应用程序运行两个不同的查询到Firebase。第一个Firebase查询显示pickerView中的数据,第二个是对“Users”集合的查询并提取自定义域。两个查询都按预期工作,pickerView显示信息,并且我能够将用户集合的结果打印到控制台。我遇到的问题是,我正在尝试将自定义域的值传递给下一个VC,但没有成功。我不确定我错过了什么。非常感谢任何帮助。下面是我的代码:

       class PatfilterVC: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

    @IBOutlet weak var hospNameTxt: UITextField!
    @IBOutlet weak var getDataBtn: UIButton!
    @IBOutlet weak var infoPickerViewer: UIPickerView!

    private var textFieldSelected = UITextField()
    private var pickerView: UIPickerView?
    private var handle: AuthStateDidChangeListenerHandle?
    private var userListener: ListenerRegistration!

    private var hospitalClass = [HospitalList]()
    private var hospCollectionRef: CollectionReference!
    private var hospCode: HospitalList! = nil

    private var loggedInUserClass = [UserSpecialty]()
    private var usersCollectionRef: CollectionReference!
    private var currentUserSpecialty: UserSpecialty! = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        overrideUserInterfaceStyle = .light

        let pickerView = UIPickerView()
        infoPickerViewer.delegate = self
        infoPickerViewer.dataSource = self

        hospNameTxt.inputView = pickerView
        hospNameTxt.delegate = self

        self.infoPickerViewer = pickerView
        self.infoPickerViewer?.delegate = self
        self.infoPickerViewer?.dataSource = self

        self.infoPickerViewer?.reloadAllComponents()

        hospCollectionRef = Firestore.firestore().collection(HOSPITAL_REF)
        usersCollectionRef = Firestore.firestore().collection(USERS_REF)

        handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
             if user == nil {
                self.getDataBtn.isUserInteractionEnabled = false
                self.infoPickerViewer.isUserInteractionEnabled = false
             } else {
                 self.getDataBtn.isUserInteractionEnabled = true
                self.infoPickerViewer.isUserInteractionEnabled = true
                 self.setListener()
             }
         })

        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
        view.addGestureRecognizer(tap)

        getHospitalList()
        getUserSpecialty()

    }


    @objc func dismissKeyboard() {
        view.endEditing(true)
    }

    override func viewWillAppear(_ animated: Bool) {
        handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
            if user == nil {

                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let LoginVC = storyboard.instantiateViewController(withIdentifier: "LoginVC")
                self.present(LoginVC, animated: true, completion: nil)
            } else {
                self.setListener()
            }
        })
    }

    override func viewWillDisappear(_ animated: Bool) {
        if userListener != nil {
            userListener.remove()
        }
    }

    func setListener() {
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        textFieldSelected = textField
    }

    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        self.pickerView?.reloadAllComponents()
        return true
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return hospitalClass.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return hospitalClass[row].hospitalName
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            hospCode = hospitalClass[row]
            let hosp = hospitalClass[row].hospitalName
            hospNameTxt.text = hosp
    }

    @IBAction func getDataTapped(_ sender: Any) {
        guard hospCode != nil else {return}
        guard currentUserSpecialty != nil else {return}

        performSegue(withIdentifier: "goToResults", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToResults" {
            let vc = segue.destination as! ResultsdataVC
            if let hosp = hospCode {
                vc.hospCodeFromVC = hosp.hospitalCode
            }
            if let user = currentUserSpecialty {
                vc.userSpecFromVC = user.userSpecialtyCode
            }
        }
    }

    //this query displays in the pickerView

    func getHospitalList() {
        let hospListQuery = hospCollectionRef?
            .order(by: HOSPITAL_NAME, descending: false)

        hospListQuery?.getDocuments { (snapshot, error) in
            if let err = error {
                debugPrint("error fetching docs: \(err)")
            } else {
                self.infoPickerViewer.reloadAllComponents()
                let snap = snapshot
                for document in snap!.documents {
                    let data = document.data()
                    let hospitalCode = data[HOSPITAL_CODE] as? String ?? ""
                    let hospitalName = data[HOSPITAL_NAME] as? String ?? ""

                    let hospList = HospitalList(hospitalCode: hospitalCode, hospitalName: hospitalName)

                    self.hospitalClass.append(hospList)
                }

            }
        }
    }

    //this query gets the values from Firebase but i cannot pass userSpecialtyCode
    // to the next viewController

    func getUserSpecialty() {
        if let loggedInUser = Auth.auth().currentUser?.uid {
            let docRef = usersCollectionRef.document(loggedInUser)
            docRef.getDocument { ( document, error) in
                if let document = document, document.exists {
                    let data = document.data()
                    let userSpecialtyCode = data?[SPECIALTY_CODE] as? String ?? ""
                    let loggedInUserId = data?[LOGGED_IN_USER_ID] as? String ?? ""

                    let loggedUser = UserSpecialty(userSpecialtyCode: userSpecialtyCode, loggedInUserId: loggedInUserId)

                    self.loggedInUserClass.append(loggedUser)
                    print("specCode", userSpecialtyCode as Any) //IT PRINTS THE CORRECT VALUE
                    print("loggedInUser", loggedInUserId as Any) //IT PRINTS THE USER ID
                } else {
                    print("no document")
                }
            }
        }
    }


    @IBAction func logoutTapped(_ sender: Any) {
        let firebaseAuth = Auth.auth()
        do {
            try firebaseAuth.signOut()

        } catch let signoutError as NSError {
            debugPrint("Error signing out: \(signoutError)")
        }
    }
}

共有1个答案

须新
2023-03-14

尝试使用这个

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToResults" {
            let vc = segue.destination as! ResultsdataVC
            _ = vc.view
            if let hosp = hospCode {
                vc.hospCodeFromVC = hosp.hospitalCode
            }
            if let user = currentUserSpecialty {
                vc.userSpecFromVC = user.userSpecialtyCode
            }
        }
    }
 类似资料:
  • 问题内容: 我想阅读onClick事件值属性。但是当我单击它时,在控制台上会看到类似以下的内容: 我的代码正常工作。运行时,我可以在onClick事件中看到但无法获取它。 我的代码: 如何在React js中将值传递给事件? 问题答案: 简单的方法 使用箭头功能: 这将创建一个新的函数,以正确的参数进行调用。 更好的方法 将其提取到子组件中。在render调用中使用箭头函数的问题是,每次都会创建一

  • 所以,我试图用discord js和sqlite3做一件事,但在过去的几个小时里,我一直在讨论这个问题,我仍然不知道如何解决它。 因此,我试图获取仅在中可用的数据,但我不知道如何将其传递出去,以便返回预期值。我已经尝试过使用全局变量,把它放在更大的范围内,但我仍然不知道如何做到这一点。 对不起,如果我弄糊涂了,我不习惯一直问问题。 编辑:应该说我正在使用NPMSqlite3模块。https://w

  • 我用jetty web server实现了这一点。 前提是web服务器已经启动。 我用JSP编写的主页试图从传入连接中获取IP地址。 因此,我将它分成两个JSP页面。(比方说,a.jsp和b.jsp) b、 jsp用于获取客户端ip地址,然后在 a、 jsp专门用于显示从b.jsp获得的ip地址。 我有一个静态字符串在我的b.jsp用于存储传入的连接IP地址。 两个问题: > 如何将值从b.jsp

  • 我一直试图从一个对象数组填充一个JTable,但是什么也没有显示出来。下面是填充表的方法代码。system.out.println使我能够检查数据是否正确传递,变量中是否有值。这是来自界面的: 即使来自接口的数据显示在控制台中,也只显示表头。如果有人能解决如何正确地将数据值传递给JTable,那就太棒了!

  • 我有这样的代码。 @RequestMapping(Value=“/Persons”,Method=RequestMethod.Post)public@ResponseBody String addUser(@RequestParam String name){ 谢谢...

  • 我是一个非程序员,有非常少的代码接触,但我想修改一个现有的代码库。我大大简化了下面的代码。请让我知道,如果我可以提供任何进一步的信息或如果这是没有意义的所有!Vocab很难。:) ClassD: