Search code examples
swiftalamofire

Queue with alamofire


I have a problem with the execution of the tasks when i use Alamofire I use two time Alamofire, a first to collect a data (token) that I will then use it to send my Post request.

The problem between my two requests, the recovery of the data is done after the second request.

import Foundation
import Alamofire
import SwiftyJSON

class Helper {
    func alomofireGet(URL: String) -> JSON {
        let queue = DispatchQueue(label: "com.test.com", qos: .background, attributes: .concurrent)
        var contenuJSON = JSON()
        Alamofire.request(URL, method: .get).responseJSON(queue: queue) { (reponse) in
            if reponse.result.isSuccess {
                contenuJSON = JSON(reponse.result.value!)
                print(contenuJSON)
            }
            else {
                contenuJSON = JSON(reponse.result.error!)
            }
        }
        return contenuJSON
    }
    func alomofirePost(URL: String, Paramaters: Dictionary<String, Any>) -> JSON {
        var contenuJSON = JSON()
        Alamofire.request(URL, method: .post, parameters: Paramaters, encoding: JSONEncoding.default).responseJSON { (reponse) in
            if reponse.result.isSuccess {
                contenuJSON = JSON(reponse.result.value!)
            }
            else {
                contenuJSON = JSON(reponse.result.error!)
            }
        }
        return contenuJSON
    }
}

In the new file = DIFFERENCE WITH CONTENT TOKEN

let request = Helper()
@IBOutlet weak var emailText: UITextField!
@IBOutlet weak var passwordText: UITextField!
override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround()
}
@IBAction func login(_ sender: Any) {
    let contenuJSON = request.alomofireGet(URL: "http://192.168.1.7/app_dev.php/login/app")
    print(contenuJSON)
    let token = contenuJSON["csrfToken"].stringValue
    print(token) // /\ EMPTY
    let Paramaters = ["_csrf_token": token, "_password": self.passwordText.text!, "_redirect_url": "", "t_path": "", "_username": self.emailText.text!]
    let contenuRequest = request.alomofirePost(URL: "http://192.168.1.7/app_dev.php/login_check", Paramaters: Paramaters)
    print(token) // /\ FULL /\
}

}


Solution

  • API call to Alamofire are the async process, hence your alamofireGet and alamofirePost returning just initialized json object - JSON() which does not have any data.

    Solution:

    You should use @escaping closure, which will hold the control until you get the result from first API call.

    func alomofireGet(URL: String, onCompletion:((JSON) -> Void)) {
        let queue = DispatchQueue(label: "com.test.com", qos: .background, attributes: .concurrent)
        var contentJSON = JSON()
        Alamofire.request(URL, method: .get).responseJSON(queue: queue) { (reponse) in
            // Load contentJSON with data
            if reponse.result.isSuccess {
                contenuJSON = JSON(reponse.result.value!)
            } else {
                contenuJSON = JSON(reponse.result.error!)
            }
            // Send contentJSON via `onCompletion` block
            onCompletion(contenuJSON)
        }
    }
    
    func alomofirePost(URL: String, Paramaters: Dictionary<String, Any>, onCompletion: @escaping ((_ response: JSON) -> Void)) {
        var contenuJSON = JSON()
        Alamofire.request(URL, method: .post, parameters: Paramaters, encoding: JSONEncoding.default).responseJSON { (reponse) in
            // Load contentJSON with data
            if reponse.result.isSuccess {
                contenuJSON = JSON(reponse.result.value!)
            } else {
                contenuJSON = JSON(reponse.result.error!)
            }
            // Send contentJSON via `onCompletion` block
            onCompletion(contenuJSON)
        }
    }
    

    Call it in your view-controller as:

        let usernameStr = self.emailText.text!
        let passwordStr = self.passwordText.text! 
    
        Helper().alomofireGet(URL: "http://192.168.1.7/app_dev.php/login/app") { contenuJSON in
            print(contenuJSON)
    
            DispatchQueue.main.async {
                let token = contenuJSON["csrfToken"].stringValue
                print(token)
    
                let Paramaters = ["_csrf_token": token, "_password": passwordStr, "_redirect_url": "", "t_path": "", "_username": usernameStr]
                Helper().alomofirePost(URL: "http://192.168.1.7/app_dev.php/login_check", Paramaters: Paramaters) { contenuJSON in
                    print(token)
                }
            }
    
        }