我正在试图找出这个完成处理程序,但我无法理解它。我有这个程序,我试图下载一个json文件并解析它。一切正常但我希望在下载和解析文件后更新UI。我必须按两次按钮才能使它工作。我知道为什么会这样。代码是异步样式,只是更新UI。我怎样才能让它等待json完成解析和下载。 感谢您提供有关此
的任何帮助和提示这是我到目前为止所做的:
@IBAction func testerClick(sender: AnyObject) {
print("Button pushed")
print("Downloading the json file")
downlaodPromoData(promoUrl, myUser: myUserName, myPass: myPassword)
}
func parsePromoJson(json : String)
{
//parse the json file
if let data = downloadJson.dataUsingEncoding(NSUTF8StringEncoding) {
let json = JSON(data: data)
for item in json[].arrayValue {
pictures.append(item["picture"].stringValue)
}
for item in json[].arrayValue{
path.append(item["path"].stringValue)
}
for item in json[].arrayValue{
label.append(item["label"].stringValue)
}
}
// Loop over the array with a for-loop.
for i in 0 ..< pictures.count {
uiResultsTextField.text.appendContentsOf("Picture: " + pictures[i] + "\n" + "Path: " + path[i] + "\n" + "Label: " + label[i] + "\n")
}
}
func downlaodPromoData(myUrl : String, myUser : String, myPass : String)
{
Alamofire.request(.GET, myUrl)
.authenticate(user: myUser, password: myPass)
.validate(statusCode: 200..<300)
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
self.downloadJson = response.result.value!
/*
.response {(request, response, data, error) in
print(response)
print(data)
print(request)
*/
}.responseJSON { response in
print("Response JSON: \(response.result.value)")
}
print("Calling parser")
parsePromoJson(downloadJson)
}
答案 0 :(得分:4)
您在请求后立即调用parsePromoJson。将parsePromoJson调用移动到Alamofire请求的responseString块内。