How can we get secondVC json value in firstVC without going to secondVC in swift

44 Views Asked by At

my firstVC json contains all other view controller json ids... here i want before pushing to other view controller i need to compare it with home home json id here which 2 ids are same i need to push thatVC.. so here without going to any other view controller how can we get their ids to compare in homeVC... please help me here.

I have tried two ways:

1) declaring variable in secondVC and assign secondVC id value to it and calling it in firstVC

in firstVC code:

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)
}

in secondVC:

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

2) storing secondVC json id with keychain wrapper and retriving it in firstVC

in first:

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)
}

in secondVC:

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

here allIdArray contain allVC ids, and sid is secondVC json id

in both ways i am getting nil why ?? i want compare secondvc id in firstvc without goning to secondvc.

please help me in above code.

1

There are 1 best solutions below

0
Starsky On

Your whole logic design isn't great, but if I was to answer straight to your question, and taking into consideration that the explanations aren't great either, here is a suggestion for you:

  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)
     }
  }