我有两个Alamofire请求。两者都可以自行工作。如何等待嵌套的Alamofire请求完成
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)
}
而且......
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")
})
}
上面的代码将无法工作,因为 “getPatientID” 功能是不完整的。我知道我知道我必须以某种方式使用派遣或完成处理程序。但我觉得这个话题非常混乱。我在这里查看了类似的解决方案,但找不到适用于我的解决方案。
两个格雷和ryantxr解决方案完美地工作。因为grez很简单,适用于我的目的,所以我会使用它(当我发布内容时,我只调用getPatientID)。似乎ryantxr解决方案在错误处理方面可能更灵活? –