2016-04-21 15 views
1

Ich habe zwei Alamofire-Anfragen. Beide funktionieren alleine gut.So warten Sie, bis eine geschachtelte Alamofire-Anfrage abgeschlossen ist

func getPatientID() { //puts patientID into patientID variable 

    UsingOauth2(drChronoOauth2Settings, performWithToken: { token in 
     Router.OAuthToken = token 
     apiCallText = "last_name=" + self.lastName.text! + "&" + "first_name=" + self.firstName.text! 
     Alamofire.request(Router.GetPatientsWithFilter()) 
      .responseJSON(completionHandler: { (result) -> Void in 
       if let data = result.data { 
        let response = NSString(data: data, encoding: NSUTF8StringEncoding) 
        self.result.text = "\(response)" 

        json = JSON(data: data) 
       } 

        self.result.text = "" 
        if json!["count"].intValue > 1 { 
         self.result.text = "more than one patient" 
         patientID = "-1" 
        } else { 
         for item in json!["results"].arrayValue { 
          patientID = item["id"].stringValue 
          self.result.text = ("Patient ID is: " + patientID!) 
        } 
       } 

      }) 

     }, errorHandler: { 
      print("Oauth2 failed") 

    }) 

view.endEditing(true) 

} 

Und ...

func postPDF() { 

    getPatientID() //NEED TO WAIT FOR COMPLETION 


    UsingOauth2(drChronoOauth2Settings, performWithToken: { token in 
     DrChronoRequestConvertible.OAuthToken = token 

     Alamofire.upload(
      .POST, 
      "https://drchrono.com/api/documents", 
      headers: ["Authorization" : "Bearer " + token], 
      multipartFormData: { multipartFormData in 

       //some multiform data including patientID from getPatientID() 

      }, 
      encodingCompletion: { encodingResult in 
       switch encodingResult { 
       case .Success(let upload, _, _): 
        upload.responseJSON { response in 
         debugPrint(response) 
         self.result.text = "Successful Upload" 
        } 
       case .Failure(let encodingError): 
        print(encodingError) 
       } 
      } 
     )   }, errorHandler: { 
      print("Oauth2 failed") 

    }) 
} 

Der obige Code wird nicht funktionieren, weil die "getPatientID" -Funktion nicht abgeschlossen ist. Ich weiß, dass ich weiß, dass ich irgendwie einen Versand- oder Vervollständigungshandler verwenden muss. Aber ich finde das Thema sehr verwirrend. Ich habe hier ähnliche Lösungen durchgesehen, finde aber keine, die für mich funktionieren.

Antwort

1

Sie können Nest der postPDF Anruf innerhalb des Abschluss-Handler von getPatientID wie folgt aus:

func getPatientID() { //puts patientID into patientID variable 

UsingOauth2(drChronoOauth2Settings, performWithToken: { token in 
    Router.OAuthToken = token 
    apiCallText = "last_name=" + self.lastName.text! + "&" + "first_name=" + self.firstName.text! 
    Alamofire.request(Router.GetPatientsWithFilter()) 
     .responseJSON(completionHandler: { (result) -> Void in 
      if let data = result.data { 
       let response = NSString(data: data, encoding: NSUTF8StringEncoding) 
       self.result.text = "\(response)" 

       json = JSON(data: data) 
      } 

       self.result.text = "" 
       if json!["count"].intValue > 1 { 
        self.result.text = "more than one patient" 
        patientID = "-1" 
       } else { 
        for item in json!["results"].arrayValue { 
         patientID = item["id"].stringValue 
         self.result.text = ("Patient ID is: " + patientID!) 
       } 
      } 

      // Now that getPatientID has completed, call the next function 
      postPDF() 

     }) 

    }, errorHandler: { 
     print("Oauth2 failed") 

}) 

view.endEditing(true) 

} 
+0

Sowohl grez und ryantxr Lösungen perfekt funktionieren. Weil Grez's so einfach ist und für meine Zwecke funktioniert, werde ich das verwenden (ich rufe nur getPatientID auf, wenn ich etwas trotzdem poste). Es scheint, dass die ryantxr-Lösung mit Fehlerbehandlung flexibler sein könnte? –

1

Sie können einen Abschluss-Handler Ihre getPatientId Funktion hinzuzufügen.

func getPatientID(completion: (id: String?) -> Void) { //puts patientID into patientID variable 

    UsingOauth2(drChronoOauth2Settings, performWithToken: { token in 
     Router.OAuthToken = token 
     apiCallText = "last_name=" + self.lastName.text! + "&" + "first_name=" + self.firstName.text! 
     Alamofire.request(Router.GetPatientsWithFilter()) 
      .responseJSON(completionHandler: { (result) -> Void in 
       if let data = result.data { 
        let response = NSString(data: data, encoding: NSUTF8StringEncoding) 
        self.result.text = "\(response)" 

        json = JSON(data: data) 
       } 

       self.result.text = "" 
       if json!["count"].intValue > 1 { 
        self.result.text = "more than one patient" 
        patientID = "-1" 
       } else { 
        for item in json!["results"].arrayValue { 
         patientID = item["id"].stringValue 
         self.result.text = ("Patient ID is: " + patientID!) 
        } 
       } 
       completion(patientID) 
      }) 

    }, errorHandler: { 
     print("Oauth2 failed") 
     completion(nil) 
    }) 

    view.endEditing(true) 
} 

Und

func postPDF() { 
    getPatientID() { 
     patientID in 
     //WILL WAIT FOR COMPLETION 

     // Make sure to handle error conditions. 
     // patientID could be nil 

     // rest of code here 

    } 
} 
Verwandte Themen