【发布时间】:2017-10-23 10:47:37
【问题描述】:
-第二次编辑- 我现在正在使用 Arpit Jain 的建议,但我该如何调用该函数?我想把函数的结果解析成一个变量。
getToken(completionHandler: { // here I should do something with in
// what should I do here to pass the result of getToken to variable?
})
-编辑过的原始问题-
我是 Swift 的新手,正在尝试实现一个 API(作为一个学习项目)。但是由于我不熟悉语法,所以我在这个 PoC 中不断收到错误。
我有一个通过 alamofire 的 http 请求,我希望 testResult 包含“成功”或错误。但是函数一直返回“空”
我不知道为什么?
func getToken() -> String{
var testResult: String! = "empty"
let url: String! = "https://the.base.url/token"
let parameters: Parameters = [
"grant_type":"password",
"username":"the_username",
"password":"the_password",
"client_id":"the_clientID",
"client_secret":"the_secret",
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding(destination: .methodDependent)).validate().responseJSON { response in
switch response.result {
case .success:
testResult = "succes"
case .failure(let error):
testResult = error as! String
}
}
return testResult // this line gives the error
}
【问题讨论】:
-
啊,对不起!在我读完这个并添加这个 var testResult: String! = "empty" 结果现在是 "empty"。似乎 alamofire 请求没有做任何事情,或者我没有将结果正确解析为字符串
-
是的,我发现请求的返回晚于函数返回的值。我会检查链接,谢谢!