我正在处理一大块Swift代码,以便通过基于Web的API提取数据。现在我很接近,但是当我在getUserInfo()中打印数据时,我认为我缺少完成处理程序方面,但是在该函数之外,会出现初始化的默认数据。该函数调用如下:
print("Provided Username is: \(workingData.user)")
getUserInfo()
print("Returned String Data is: \(workingData.responseDataString)")
和实际功能:
func getUserInfo() {
Alamofire.request(workingjss.jssURL + devAPIMatchPath + workingData.user, method: .get)
.authenticate(user: workingjss.jssUsername, password: workingjss.jssPassword).responseString { response in
if (response.result.isSuccess) {
print("In Function Data: \(response.result.value!)"
workingData.responseDataString = response.result.value!
}
}
}
运行代码的输出是:
Provided Username is: MYUSER
Returned String Data is: Nothing Here Yet
In Function Data: {"Cleaned JSON Data here"}
完成处理程序会帮助解决问题吗?我很高兴与Alamofire合作,很抱歉,如果这很容易。谢谢!
答案 0 :(得分:8)
尝试使用完成处理程序:
func getUserInfo(completion: @escaping (String) -> Void) {
Alamofire.request(workingjss.jssURL + devAPIMatchPath + workingData.user, method: .get)
.authenticate(user: workingjss.jssUsername, password: workingjss.jssPassword).responseString { response in
if (response.result.isSuccess) {
print("In Function Data: \(response.result.value!)"
completion(response.result.value!)
}
}
}
并称之为:
getUserInfo() { response in
// Do your stuff here
workingData.responseDataString = response
print("Returned String Data is: \(workingData.responseDataString)")
}