2016-11-07 39 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