【发布时间】:2016-11-07 23:19:22
【问题描述】:
这听起来像是一个非常愚蠢的问题,但我对 swift 还很陌生,无法思考如何解决这个问题。正如您在此Screenshot 中看到的那样,我在RecipesViewController 中有一个搜索食谱文本字段,用户在其中输入食物(我在api 调用中使用)。用户点击按钮后,我调用 api 并从该 api 获取数据并将该数据存储在我的 RecipesViewController 类中的实例变量(searchRecipe 数组)中。现在我试图在表格视图中显示我从 api 收到的数据,所以我有另一个名为 SearchRecipeTViewController 的类。在这个类中,我想用从 api 收到的数据填充表,但是当我尝试访问 searchRecipe 数组(存储从 api 接收的元素)时,我得到一个空白值,我理解这是由于实例变量被初始化为“”。但是现在我该怎么做才能从 api 获取数据并在用户点击按钮时将其显示在 table view 上。任何建议,将不胜感激。
点击按钮时调用api获取数据的代码
@IBAction func SearchButton(sender: UIButton) {
if let recipe = RecipeSearchBar.text {
searchRecipe = recipe
}
//search recipe API call
endpoint = "http://api.yummly.com/v1/api/recipes? _app_id=apiID&_app_key=apiKey&q=\(searchRecipe)"
Alamofire.request(.GET, endpoint).responseJSON { response in
if response.result.isSuccess {
let data = response.result.value as! NSDictionary
if let matches = data["matches"] as? [[String: AnyObject]] {
for match in matches {
if let name = match["recipeName"] as? String {
self.recipeName.append(name);
}
}
}
}
else if response.result.isFailure {
print("Bad request")
}
}
}
【问题讨论】:
标签: swift uitableview uibutton