0

I'm beginner in iOS swift.
I have a problem: when I do a network request, the compiler executed the code below without waiting the server response.

func callingRiderLoginCopy(userID: String, Password:String, completeCode: Int)  {


    print("I am in callingRiderLoginCopy And Complete verification Code is \(completeCode)")


    let parameters : [String : Any] = ["userId": userID, "password": Password, "verificationCode": completeCode]

    guard let url = URL(string: "\(Constents.baseURL)/rider/logIn") else {
        print("Invalid URL")
        return
    }


    AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default)
        .responseJSON { response in
            switch response.result {
            case .success:
                if let result = response.data {
                    do {

                        let resultIs = try JSONDecoder().decode(RiderLoginCopy.self, from:result)
                        self.riderSuc = resultIs.success // Strore the success state in riderSuc

                        print("Data is riderSuc ** \(self.riderSuc)")

                        if let results = resultIs.user {

                            print("This data came from RiderLoginCopy API : \(resultIs)")

                            self.setToken = KeychainWrapper.standard.set(resultIs.token!, forKey: "token")
                            self.retrivedToken = KeychainWrapper.standard.string(forKey: "token")!
                            print("Retrived Token ::: \(self.retrivedToken)")

                        }

                    } catch {
                        print(error)

                    }

                }

            case .failure(let error):
                print(error)

            }            
    }

}


@IBAction func verifyAct(_ sender: UIButton) {

    let userId = enteredUserID
    KeychainWrapper.standard.string(forKey: "Password")!
    let password = enteredPassword
    KeychainWrapper.standard.string(forKey: "UserID")!

    let completeCode:Int = Int(textField1.text! + textField2.text! + textField3.text! + textField4.text!)!

        self.callingRiderLoginCopy(userID: userId, Password: password, completeCode: completeCode)

        if self.riderSuc == 1 {

                    let storyboard = UIStoryboard(name: "Rider", bundle: nil)
                    let vc = storyboard.instantiateViewController(withIdentifier: "signin2VC") as! SignIn2VC
                vc.verifyCode = completeCode
                    self.navigationController?.pushViewController(vc, animated: true)

                }else{
                    print("Plese Try Try again RiderSuc is not equal to 1 !: ")
                }
}
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
Hanzla Rafique
  • 63
  • 1
  • 10
  • Does this answer your question? [Returning data from async call in Swift function](https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function) – Joakim Danielson Jun 03 '20 at 13:12

1 Answers1

0

Use a closure completionHandler: parameter in your function definition of type (String?) -> Void to know when the response is received and then proceed with the rest of the code.

Modify your function from:

func callingRiderLoginCopy(userID: String, Password: String, completeCode: Int) {

To this:

func callingRiderLoginCopy(userID: String, Password:String, completeCode: Int, completionHandler: @escaping (String?) -> Void)  {

And return the retrivedToken when it's received successfully and return nil when it's not.

And when you call this method modify your call from this:

self.callingRiderLoginCopy(userID: userId, Password: password, completeCode: completeCode)

To this:

self.callingRiderLoginCopy(userID: userId, Password: password, completeCode: completeCode) { token in
    // Do stuff related to token
}
Frankenstein
  • 15,732
  • 4
  • 22
  • 47