我们如何在firstVC中获取secondVC json值而又不快速进入secondVC

时间:2019-10-02 11:34:40

标签: json swift pushviewcontroller keychainitemwrapper

我的firstVC json包含所有其他视图控制器json ID ...在这里,我想在推送到其他视图控制器之前,我需要将其与home home json ID进行比较,这里我需要推送2VC的ID是相同的。无需使用任何其他视图控制器,我们如何获取其ID以在homeVC中进行比较...请在这里帮助我。

我尝试了两种方法:

1)在secondVC中声明变量并为其分配secondVC id值,然后在firstVC中调用它

在firstVC代码中:

let goVC = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController

var goId: String = goVC.secndId ?? ""
print("the goid is \(goId)")// getting nil
if(goId == allIdArray)
{
    self.navigationController?.pushViewController(goVC, animated: true)
}

在secondVC中:

var secndId: String?
secndId = jsonObj["sid"] as? String

2)使用钥匙串包装器存储secondVC json id并在firstVC中检索它

首先:

let goVC = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController

let goId: String = KeychainWrapper.standard.string(forKey: "sid") ?? ""
print("the goid is \(goId)")// getting nil
if(goId == allIdArray)
{
    self.navigationController?.pushViewController(goVC, animated: true)
}

在secondVC中:

var secndId: String?
self.secndId = jsonObj["sid"] as? String
KeychainWrapper.standard.set(self.secndId ?? "", forKey: "sid")

此处allIdArray包含allVC id,而sid是secondVC json ID

在两种方式下,我都为零,为什么?我想在firstvc中比较secondvc id而不必转到secondvc。

请帮我处理上面的代码。

1 个答案:

答案 0 :(得分:0)

您的整个逻辑设计不是很好,但是如果我直接回答您的问题,并且考虑到解释也不是很好,那么这里有个建议:

  let vcID = 1

  let viewControllers = [1 : FirstVC.self, 2 : SecondVC.self, 3 : ThirdVC.self]
  for (id, vcType) in viewControllers {
     if id == vcID {
         //assuming that you assign storyboard identifiers exactly matching classes' names, otherwise this guard statement won't succeed
         guard let goToVC = storyboard?.instantiateViewController(withIdentifier: "\(vcType)") else { return }
         //if you need to pass any data before you present this VC, then you will need to safely cast into known VC types
         self.present(goToVC, animated: true, completion: nil)
     }
  }