我试图创建一个从json api获得相应的函数,但函数返回的值比alamofire请求更快......有人可以帮助我吗?非常感谢你。代码如下。
func trainNameToTelecode(trainName: String) -> String {
var returnTelecode: String = ""
Alamofire.request("http://tra.ink/api/query/train?name=\(trainName)").responseJSON { (response) in
let result = response.result
guard let resultDict = result.value as? Dictionary<String,AnyObject> else {return}
guard let bodyDict = resultDict["body"] as? [String:AnyObject] else {return}
returnTelecode = bodyDict["telecode"] as! String
}
return returnTelecode
}
答案 0 :(得分:1)
您可以使用完成处理程序,在您的请求完成时返回字符串,例如:
func trainNameToTelecode(trainName: String, completion: (String) -> Void) {
Alamofire.request("http://tra.ink/api/query/train?name=\(trainName)").responseJSON { (response) in
let result = response.result
guard let resultDict = result.value as? Dictionary<String,AnyObject> else {return}
guard let bodyDict = resultDict["body"] as? [String:AnyObject] else {return}
if let returnTelecode = bodyDict["telecode"] as? String {
completion(returnTelecode)
} else {
completion("telecode is nil")
}
}
}
//and where you call your function:
self.trainNameToTelecode(trainName: "yourName") { (telecode) in
print(telecode)
}