##API
{ result: [ { foodImageUrl: "https://image.space.rakuten.co.jp/d/strg/ctrl/3/fbd7dd260d736654532e6c0b1ec185a0cede8675.49.2.3.2.jpg", recipeDescription: "そのままでも、ご飯にのせて丼にしても♪", recipePublishday: "2017/10/10 22:37:34", shop: 0, pickup: 0, recipeId: 1760028309, nickname: "はぁぽじ", smallImageUrl: "https://image.space.rakuten.co.jp/d/strg/ctrl/3/fbd7dd260d736654532e6c0b1ec185a0cede8675.49.2.3.2.jpg?thum=55", recipeMaterial: [ "鶏むね肉", "塩", "酒", "片栗粉", "○水", "○塩", "○鶏がらスープの素", "○黒胡椒", "長ネギ", "いりごま", "ごま油" ], recipeIndication: "約10分", recipeCost: "300円前後", rank: "1", recipeUrl: "https://recipe.rakuten.co.jp/recipe/1760028309/", mediumImageUrl: "https://image.space.rakuten.co.jp/d/strg/ctrl/3/fbd7dd260d736654532e6c0b1ec185a0cede8675.49.2.3.2.jpg?thum=54", recipeTitle: "ご飯がすすむ!鶏むね肉のねぎ塩焼き" },
##やりたいこと
foodImageUrlをとってtableviewに表示させたい。
##試したコード
import UIKit struct ResultUserList: Codable { var result: User struct User: Codable{ var foodImageUrl: String } } class ResultViewModel { static func fetchArticle(completion: @escaping ([ResultUserList]) -> Swift.Void) { let url = "https://app.rakuten.co.jp/services/api/Recipe/CategoryRanking/20170426?format=json&applicationId=1095609837981916624" guard var urlComponents = URLComponents(string: url) else { return } //URLQueryItemを使うことでURLのクエリストリングを追加して、ページの要素数を50までと指定 urlComponents.queryItems = [ URLQueryItem(name: "per_page", value: "50"), ] let task = URLSession.shared.dataTask(with: urlComponents.url!) { data, response, error in guard let jsonData = data else { return } do{ let articles = try JSONDecoder().decode([ResultUserList].self, from: jsonData) completion(articles) } catch { print(error.localizedDescription) } } task.resume() } } class ViewController: UIViewController { private var tableView = UITableView() fileprivate var articles: [ResultUserList] = [] override func viewDidLoad() { super.viewDidLoad() self.title = "レシピ" tableView.dataSource = self tableView.frame = view.frame view.addSubview(tableView) ResultViewModel.fetchArticle(completion: { (articles) in self.articles = articles DispatchQueue.main.async { self.tableView.reloadData() } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell") let article = articles[indexPath.row] cell.textLabel?.text = article.result.foodImageUrl return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return articles.count } }
よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー