Очередь с Аламофиром - PullRequest
       5

Очередь с Аламофиром

0 голосов
/ 17 сентября 2018

У меня проблема с выполнением задач при использовании Alamofire Я использую Alamofire два раза, сначала для сбора данных (токена), которые затем буду использовать для отправки моего запроса Post.

Проблема между моими двумя запросами, восстановление данных производится после второго запроса.

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
    }
}

В новом файле = РАЗНИЦА С ЖЕЛЕЗОМ КОНТЕНТА

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 /\
}

}

1 Ответ

0 голосов
/ 17 сентября 2018

API-вызов Alamofire - это асинхронный процесс, поэтому ваши alamofireGet и alamofirePost возвращают только что инициализированный объект json - JSON(), который не имеет никаких данных.

Решение:

Вам следует использовать @escaping closure, который будет удерживать элемент управления до тех пор, пока вы не получите результат от первого вызова API.

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)
    }
}

Назовите его в вашем view-controller как:

    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)
            }
        }

    }
...