Search code examples
iosobjective-cswiftalamofirerx-swift

How to pass data in a closure to another scene


It is my first app in swift. I am using Alamofire for my HTTP request. Coming from Android, I know it is possible to attach serialized object to navcontroller action while navigating from one screen to another.

I want to be able to perform segue after from the viewmodel subscription and attach the resultant token to the segue as I will be using it for verification at the next screen.

I have tried didSet but to no avail.

How can I do this in swift.


    //MARK: Register user
    @IBAction func registerUser(_ sender: Any) {

        let fullName = firstNameTF.text! + " " + lastNameTF.text!
        let email = emailTF.text
        let password = passwordTF.text
        let phone = phoneNumberTF.text
        let country = countryDropDown.text

        let user = User(name: fullName, email: email, password: password, country: country, phone: phone, token: nil)

        var tk = ""{
            didSet{
                token = tk
            }
        }
      authViewModel.registerUser(user: user).subscribe(onNext: { (AuthResponse) in
            print("messaage \(String(describing: AuthResponse.message))")
            self.tokens = AuthResponse.token
            self.performSegue(withIdentifier: "gotoVerification", sender: self)
        }, onError: { (Error) in
            print("Error: \(Error.localizedDescription)")
        }, onCompleted: nil) {

        }.disposed(by: disposeBag)

        print("token \(token)")
//        AF.request(url, method: .post, parameters: user, encoder: JSONParameterEncoder.default).responseDecodable(of:AuthResponse.self){response in
//
//            response.map { (AuthResponse) in
//                print("messaage \(String(describing: AuthResponse.message))")
//            }
//
//            print("user: \(user)")
//            print("response \(String(describing: response))")
//        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc = segue.destination as? UserVerification{
//
            vc.tokens = token
            print("token \(token)")
        }
    }


Solution

  • You can pass the token as the sender:

    self.performSegue(withIdentifier: "gotoVerification", sender: AuthResponse.token)
    

    Then:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc = segue.destination as? UserVerification, let token = sender as? String {
            vc.tokens = token
            print("token \(token)")
        }
    }