【问题标题】:Swift dealing with classes, UIButtons and tableViewSwift 处理类、UIButtons 和 tableView
【发布时间】: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


    【解决方案1】:

    尝试使用 SwiftyJSON 来操作 API 返回的 JSON。 SwiftyJSON 使使用 JSON 的 API 调用变得更加容易。这是我使用的同时使用 Alamofire 和 SwiftyJSON 的代码。

    //Use alamofire to connect to the web service and use GET on it
        Alamofire.request(url).responseJSON { response in
            if let error = response.result.error {
                print("Error: \(error)")
                return
            }
    
            //Value is the response the webservice gives, given as a Data Obkect
            if let value = response.result.value {
                //The information given from the webservice in JSON format
                let users = JSON(value)
                print("The user information is: \(users)")
    
                //Get each username in the JSON output and print it
                for username in users.arrayValue{
                    print(username["username"].stringValue)
                }
            }
        }
    

    忘记添加指向 SwiftJSON 的链接:https://github.com/SwiftyJSON/SwiftyJSON

    【讨论】:

    • 那不回答我的问题我能够从 API 中提取我想要的内容。
    猜你喜欢
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多