2017-10-20 29 views
-1

J'essaie actuellement d'extraire des données du serveur. Pour ce faire, je dois créer un objet JSON (req1) et l'envoyer en tant que requête à la première API. Ensuite, l'API me renvoie un JSON (res1). A partir de ce JSON (res1), je dois extraire des données (très longues, appelons-les Data1) et créer un autre objet JSON (req2) et frapper une autre API avec une requête et attendre une réponse (res2).Gestion des messages HTTP Retour au début SWIFT 4.0

Maintenant, c'est une fonction dos à dos. Lorsque j'appelle la première API, il faut beaucoup de temps pour répondre et à ce moment-là, ma deuxième API est appelée. Ainsi, j'obtiens une erreur du serveur. Comment devrais-je venir ici?

ALGO:

  1. Appel API_A()
  2. reçu JSON_A
  3. Extrait JSON_A 4.Call API_B (JASON_A.someparts)
  4. reçu JSON_B
  5. Extrait JSON_B

Voici ci-dessous le code:

let json1 = JSON() 
 
let json2 = JSON() //my final result 
 

 
override func viewDidLoad() { 
 
     super.viewDidLoad() 
 
\t  firstApiHit {() ->() in 
 
      secondApiHit(jsonV: json1) 
 
     } 
 
    } 
 

 
func firstApiHit(handleComplete:(()->())){ 
 
\t let url1 = URL(string : firstApiURL) 
 
\t let json: [String: String] = ["Data1:Data1Rest"] 
 
\t let jsonData = try? JSONSerialization.data(withJSONObject: json) 
 
\t json1 = httpPost(jsonData: jsonData!, url: url1!) //hit to the first API! 
 
\t handleComplete() 
 
} 
 

 
func secondApiHit(jsonV : JSON){ 
 
\t let url1 = URL(string : secondApiURL) 
 
\t var value = String() 
 
\t extractedValue = String(describing:jsonV["DataX"]) 
 
\t var json = [String: String]() 
 
\t json = ["Data1":extractedValue] 
 
\t let jsonData = try? JSONSerialization.data(withJSONObject: json) 
 
    let json2 = httpPost(jsonData: jsonData!, url: url2!) // my final result! 
 
\t \t //Need the json2 as the final Result!! 
 
} 
 
    
 
func httpPost(jsonData: Data, url: URL) -> JSON { 
 
\t if !jsonData.isEmpty { 
 
\t \t var request = URLRequest(url: url) 
 
\t \t request.httpMethod = "POST" 
 
\t \t request.httpBody = jsonData 
 
\t \t request.setValue("application/json", forHTTPHeaderField: "Content-Type") 
 
\t \t URLSession.shared.getAllTasks { (openTasks: [URLSessionTask]) in 
 
\t \t \t \t \t \t \t \t \t print("open tasks: \(openTasks)") 
 
\t \t \t \t \t \t \t \t \t } 
 
\t \t let task = URLSession.shared.dataTask(with: request) { data, response, error in 
 
\t \t \t \t \t \t \t \t \t \t \t \t \t \t guard let data = data, error == nil else { 
 
\t \t \t \t \t \t \t \t \t \t \t \t \t \t \t // check for fundamental networking error 
 
\t \t \t \t \t \t \t \t \t \t \t \t \t \t \t print("error=\(String(describing: error))") 
 
\t \t \t \t \t \t \t \t \t \t \t \t \t \t \t return 
 
\t \t \t \t \t \t \t \t \t \t \t \t \t \t } 
 
    \t \t  \t if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   
 
\t \t \t \t \t // check for http errors 
 
\t \t \t \t print("statusCode should be 200, but is \(httpStatus.statusCode)") 
 
\t \t \t \t print("response = \(String(describing: response))") 
 
\t \t \t } 
 
\t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t 
 
\t \t \t let jsonX = JSON(data: data) //extracting the data! 
 
\t \t } \t 
 
    \t task.resume() 
 
\t } 
 
    return jsonM 
 
}

+2

"Ainsi, j'obtiens une erreur du serveur" - Pourquoi "ainsi"? Quelle est la raison? Quel genre d'erreur? – Raphael

+0

Vous voudrez peut-être vérifier Alamofire. – Raphael

+0

L'erreur est que, je ne peux pas extraire l'ensemble du JSON de la première réponse et ainsi, ma deuxième demande est incomplète, entraînant la deuxième réponse étant l'échec! Échec comme dans j'obtiens un code 400, au lieu de 200 et ainsi mon JSON revient comme nul. – Stopshe

Répondre

0

httpPost(...) Rendements avant URLSession.shared.dataTask(...) est terminée, car celui-ci est exécuté de façon asynchrone.

Dans firstApiHit(...), vous ne devez pas appeler handleComplete(), mais le transmettre à httpPost(...). Vous devez également transmettre le JSON en tant que paramètre.

override func viewDidLoad() { 
    super.viewDidLoad() 
    firstApiHit { json in 
     secondApiHit(jsonV: json) 
    } 
} 

func firstApiHit(handleComplete: JSON -> Void){ 
    ... 
    json1 = httpPost(jsonData: jsonData!, url: url1!, handleComplete) 
} 

func httpPost(jsonData: Data, url: URL, responseHandler: (JSON) -> Void) { 
    let task = URLSession.shared.dataTask(with: request) { data, response, error in 
     ...         
     let jsonX = JSON(data: data) 
     responseHandler(jsonX) 
    } 
} 

Vous certainement besoin d'apprendre comment utiliser les fermetures et, plus précisément, le modèle de gestionnaire de réponse. Sinon, vous serez dans un monde de douleur encore et encore.