0

First view Controller

class ViewController: UIViewController {

    @IBOutlet weak var txt: UITextField!
    
    var jsonview = JsonViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
    }
    @IBAction func loginBtn(_ sender: UIButton) {
       // jsonview.getData()
        
            let dataOne = txt.text
              let vc = self.storyboard?.instantiateViewController(identifier: "JsonViewController") as! JsonViewController
              vc.dataTwo = dataOne!
              self.navigationController?.pushViewController(vc, animated: true)
    }
    
    
}

Another View Controller

class JsonViewController: UIViewController {

    @IBOutlet weak var nameTxt: UILabel!
    @IBOutlet weak var ageTxt: UILabel!
    @IBOutlet weak var placeTxt: UILabel!
    
    var dataTwo = ""
     
    override func viewDidLoad() {
        super.viewDidLoad()
        nameTxt.text = dataTwo
     
    }
    func getData(){
        guard let path = Bundle.main.path(forResource: "example", ofType: "json") else {
            return
        }
        
        let url = URL(fileURLWithPath: path)
        
        do{
            let data = try Data(contentsOf: url)
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
            
            guard let array = json as? [Any] else {
                return
            }
            for user in array{
                guard let userDict = user as? [String:Any] else {return}
                guard let Name = userDict["Name"] as? String else { return}
                guard let Age = userDict["Age"] as? String else { return}
                guard let Place = userDict["Place"] as? String else { return}
                
                
                if dataTwo.contains(Name){
                    nameTxt.text = Name
                    ageTxt.text = Age
                    placeTxt.text = Place
            }
            }
        }catch{
            print(error)
        }
    
}
}

How do I fetch JSON data to another view controller by tapping a button on the first view controller?

Thanks in advance....!!

Raja Kishan
  • 16,767
  • 2
  • 26
  • 52
ThE 2K KiD
  • 43
  • 1
  • 5
  • Do you know the difference between `viewDidLoad` and `viiewWillAppear`? – El Tomato May 25 '21 at 04:29
  • I don't understand the question. What is the desired outcome here? – Daniel T. May 25 '21 at 04:52
  • I have data in Json file I wanna fetch that data to another view controller I mean in the first view controller i added a textField and button if i enter the name in text field and when i tap the button it has to redirect to the another view controller and it has to show the details of the the name of the person which i entered in the previous view controller In the second view controller i have 3 labels which shows me the name, age and place... Thanks in advance :) – ThE 2K KiD May 25 '21 at 09:22

0 Answers0