Search code examples
iosswift3oauth-2.0alamofireswifty-json

how to pass JSON data from login view to multiple view controller, is it possible or not?


i am trying to pass JSON data in two different view controllers using perfrom segue and it is easy to pass data to single view controller or it is possible or not ?

func getlogin(){
        let headers = [
            "Content-Type": "application/x-www-form-urlencoded"
        ]
        let parameters = [

            "UserName": username_textfield.text! as String,
            "Password": password_textfield.text! as String,
            "grant_type": "password",
            ]


        //        let url = NSURL(string: "http://192.168.100.5:84/Token")!
        Alamofire.request("http://192.168.100.5:84/Token", method: .post, parameters: parameters, encoding:  URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in

            switch(response.result) {
            case.success(let data):
                print("success",data)
                 let statusCode = (response.response?.statusCode)!

//                self.myResponse = JSON(data)
//                let login = Login(loginJson: self.myResponse)

                if statusCode == 200{
                    self.view.makeToast(message: "Welcome !!")

                    self.myResponse = JSON(data)
                    let login = Login(loginJson: self.myResponse)
                    DispatchQueue.main.async(execute: { () -> Void in
                        self.performSegue(withIdentifier: "dashboard", sender: login)
                        self.performSegue(withIdentifier: "rear_view", sender: login)

                    })

//
                }else{
                    self.view.makeToast(message: "Username or password invalid")
                }



            case.failure(let error):
                print("Not Success",error)
                self.view.makeToast(message: "Server Error!!")
            }

        }
    }

and my prepare segue from where i am trying to pass my JSON data ?

override  func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "dashboard" {
            let navController = segue.destination as! UINavigationController
            if let detailController = navController.topViewController as? ViewController,
                let loginData = sender as? Login {
                detailController.login_details = loginData
            }


 }
    if segue.identifier == "rear_view" {

        let navController = segue.destination as! UINavigationController
        if let dc = navController.topViewController as? MenuDrawerViewController,
                        let loginData = sender as? Login {
                        dc.login_details = loginData
                    }

    }
}

while user logs in JSON data is passed to viewController but not passing to MenuViewController , trying to pass data in both view controllers , how this issue can be solve ? or need some suggestions ?


Solution

  • Since you can only segue to a single controller, you cannot directly pass data to several ViewControllers in prepare(for segue). However, you have several methods to pass data between several view controllers.

    1. Persist the data on disk, if it is not too complex and big, you can just store it in UserDefaults from your initial view controller and then access UserDefaults from your other two view controllers. If the data is more complex, you might have to use a database framework (Realm or CoreData for example).
    2. You can create static properties of your classes if you don't need to pass the data to a specific class instance, which you can access from all of your view controllers.
    3. Pass the data needed for both of your view controllers through the segue from your first view controller and then pass the data needed for your 3rd view controller when you segue from your 2nd one. However, this only works with a small number of view controllers and only if you can only segue to a view controller from the one to which you sent the data previously.

    Edit: example on using static properties:

    class FirstVC: UIViewController {  //this is your initial view controller
        ...
        let login = Login(loginJson: self.myResponse)
                    ThirdVC.login = loginData
                    DispatchQueue.main.async(execute: { () -> Void in
                        self.performSegue(withIdentifier: "dashboard", sender: login)
                    })
        ...
    }
    
    class SecondVC: UIViewController {  // you segue here from FirstVC
    
    }
    
    class ThirdVC: UIViewController { //you segue here from SecondVC
        static var login: Login?
        override function viewDidLoad(){
           super.viewDidLoad()
           print(ThirdVC.login) // you can access the data sent from your FirstVC like this anywhere in ThirdVC.
        }
    }