首页 > 解决方案 > 无法将 autoID 传递给新的 VC

问题描述

我正在尝试将收到的 autoID 传递给另一个 ViewController ......我得到这样的 ID:

var passID: String = ""

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    jobsRef.queryOrdered(byChild: "userID").queryEqual(toValue: userID).observe(.childAdded, with: {snapshot in
        let currentPostID = snapshot.key
        self.passID = currentPostID
        print(self.passID) //-> Here the ID gets printed correctly
    })
    performSegue(withIdentifier: "toJobDetail", sender: indexPath)
}

我的 Segue 本身看起来像这样:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "toJobDetail" {
        if let indexPath = sender as? IndexPath, let nextVC = segue.destination as? MyProfileJobDetailViewController {
            nextVC.jobDetails = MyProfileJobDetailViewController.JobDetails(IDPassed: self.passID)
   }}}

我尝试像这样在 New VC 中打印 ID:

var jobDetails: JobDetails?
struct JobDetails {
    var IDPassed: String
}

override func viewDidLoad() {
    super.viewDidLoad()
    print(jobDetails?.IDPassed) -> ID won't get printed correctly 
 }

但我现在的输出只有:

选修的(())

我在传递 ID 时做错了什么吗?因为在选择单元格时打印 ID 有效....

编辑:

我现在正在获取 ID,因为我只是在 Firebase 查询中调用 performSegue:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    jobsRef.queryOrdered(byChild: "userID").queryEqual(toValue: userID).observe(.childAdded, with: {snapshot in
        let currentPostID = snapshot.key
        self.passID = currentPostID
        print(self.passID)
        self.performSegue(withIdentifier: "toJobDetail", sender: indexPath)
    })
}

标签: iosswiftfirebasefirebase-realtime-database

解决方案


您的查询是异步的并且需要一些时间,您应该确保在移动到下一个屏幕之前拥有所需的值。试试这个..

jobsRef.queryOrdered(byChild: "userID").queryEqual(toValue: userID).observe(.childAdded, with: {snapshot in
    let currentPostID = snapshot.key
    self.passID = currentPostID
    print(self.passID) //-> Here the ID gets printed correctly
    performSegue(withIdentifier: "toJobDetail", sender: indexPath)
})

编辑:

试试看……

var jobDetails: JobDetails? {
   didSet {
      print("set jobDetails to \(jobDetails)"
   }
}

override func viewDidLoad() {
    super.viewDidLoad()
    print("viewDidLoad: \(jobDetails?.IDPassed)")
 }

推荐阅读