2016-11-07 63 views
0

这可能听起来像一个非常愚蠢的问题,但我对swift很陌生,无法思考如何去做这件事。如您在Screenshot中看到的,我在RecipesViewController中有一个搜索食谱文本字段,用户可以在其中输入食品(我在api调用中使用该食品)。在用户点击按钮后,我调用api并从该api获取数据,并将该数据存储在我的RecipesViewController类的实例变量(searchRecipe数组)中。现在我正试图在一个表视图中显示我从api收到的数据,所以我有另一个名为SearchRecipeTViewController的类。在这个类中,我希望使用从api收到的数据填充表,但是当我尝试访问searchRecipe数组(它存储从api接收到的元素)时,我得到一个空白值,我知道它是由实例变量被初始化为“”。但是现在我该如何解决这个问题,以便我可以从api获取数据并在用户点击按钮时将其显示在桌面视图中。任何建议,将不胜感激。Swift处理类,UIButtons和tableView

代码来调用和按钮被点击

@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") 
     } 
    } 
} 

回答

-1

当从API获取数据,请尝试使用SwiftyJSON操纵JSON API返回。 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

+0

这并不回答我的问题,我能提取我从API希望。 – smriti