2017-02-18 2 views
1

В настоящее время я пытаюсь отобразить данные 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 
} 

Спасибо заранее! :)

ответ

0

для этого вы должны сделать расширение ImageView в

extension UIImageView { 
    func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) { 
     contentMode = mode 
     URLSession.shared.dataTask(with: url) { (data, response, error) in 
      guard 
       let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, 
       let mimeType = response?.mimeType, mimeType.hasPrefix("image"), 
       let data = data, error == nil, 
       let image = UIImage(data: data) 
       else { return } 
      DispatchQueue.main.async() {() -> Void in 
       self.image = image 
      } 
      }.resume() 
    } 
    func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) { 
     guard let url = URL(string: link) else { return } 
     downloadedFrom(url: url, contentMode: mode) 
    } 
} 

, то вы должны написать метод cellForRowAt, как

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "recipeCell", for: indexPath) 
    let recipe = recipes[indexPath.row] 
    let imagePath = recipe.image 
    cell.titleLabel.text = recipe.title 
    cell. imgView.downloadedFrom(link: imagePath) 

     return cell 
    } 
+0

не забудьте перезагрузить таблицу, когда вы получите ответ от сервера – Ram

+0

Спасибо, я смог использовать расширение и получить изображениеURL, которое будет распознано в UIImageView. – Chace

Смежные вопросы