В настоящее время я пытаюсь отобразить данные JSON на моем UITableView. Я создал отдельный класс, который обрабатывает и объявляет данные, извлекаемые из API. Я также создал пользовательскую ячейку для отображения данных. Однако я не уверен, как отображать изображения API. Я был в состоянии отобразить название API, используя только стандартный TableViewController без пользовательских ячеек:Отображение JSON imageURL в UITableView с использованием Alamofire и SwiftyJSON
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "recipeCell", for: indexPath)
cell.textLabel?.text = recipes = [indexPath.row].title
return cell
}
но при попытке создать пользовательскую ячейку в изображения использует ImageUrl, который работает по-разному. Другие учебники и демо не используют Alamofire и SwiftyJSON.
Я прочитал документацию: https://github.com/SwiftyJSON/SwiftyJSON#integration, но все еще не уверен, как решить эту проблему. Скажите, пожалуйста, как вы получите данные API для отображения на моем столе.
Класс
import Foundation
import SwiftyJSON
class Recipe {
var title: String!
var image: URL?
init(json: JSON) {
self.title = json["title"].stringValue
self.image = json["image"].url
}
}
CustomCell
import UIKit
class RecipeCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var imgView: UIImageView?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
ViewController
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Alamofire.request(searchURL, method: .get, parameters: params, encoding: URLEncoding.default, headers: headers).response { [unowned self] response in
guard let data = response.data else { return }
let json = JSON(data: data)
for recipe in json.arrayValue {
let newRecipe = Recipe(json: recipe)
self.recipes.append(newRecipe)
}
for recipe in self.recipes {
print(recipe.title)
print(recipe.image)
}
}
}
// Display JSON Data into the tableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "recipeCell", for: indexPath)
// What to write here?
return cell
}
Спасибо заранее! :)
не забудьте перезагрузить таблицу, когда вы получите ответ от сервера – Ram
Спасибо, я смог использовать расширение и получить изображениеURL, которое будет распознано в UIImageView. – Chace