0

swift 3 json from url can't problem to get cell uitableview

Episode.swift

    import Foundation

    class Episode
    {
    var title: String?
    var description: String?
    var thumbnailURL: URL?
    var createdAt: String?
    var author: String?
    var url: URL?
    var episodes = [Episode]()

    init(title: String, description: String, thumbnailURL: URL, createdAt:   String, author: String)
    {
        self.title = title
        self.description = description
         self.thumbnailURL = thumbnailURL
        self.createdAt = createdAt
        self.author = author
    }

    init(espDictionary: [String : AnyObject])
    {
        self.title = espDictionary["title"] as? String

        description = espDictionary["description"] as? String
        thumbnailURL = URL(string: espDictionary["thumbnailURL"] as! String)
        self.createdAt = espDictionary["pubDate"] as? String
        self.author = espDictionary["author"] as? String
        self.url = URL(string: espDictionary["link"] as! String)
    }

    static func downloadAllEpisodes() -> [Episode]
    {
        var episodes = [Episode]()
        let url = URL(string:"http://pallive.xp3.biz/DucBlog.json")

            URLSession.shared.dataTask(with: url!) { (data, response, error) in

                if error != nil {
                    print(error)
                    return
                }

                else {

                    if let jsonData = data ,let jsonDictionary = NetworkService.parseJSONFromData(jsonData) {

                        let espDictionaries = jsonDictionary["episodes"] as! [[String : AnyObject]]

                        for espDictionary in espDictionaries {


                         let newEpisode = Episode(espDictionary: espDictionary)                            
                            episodes.append(newEpisode)                               

                      }
                    }                        
                     }                       
                }

                .resume()

          return episodes
          }    
}

EpisodeTableViewCell.swift

import UIKit

class EpisodeTableViewCell: UITableViewCell
{        
    var episode: Episode! {
        didSet {
            self.updateUI()
            print(episode)
        }
    }

    func updateUI()
    {
        titleLabel.text = episode.title
        print(episode.title)
        authorImageView.image = UIImage(named: "duc")
        descriptionLabel.text = episode.description
        createdAtLabel.text = "yosri hadi | \(episode.createdAt!)"

        let thumbnailURL = episode.thumbnailURL
        let networkService = NetworkService(url: thumbnailURL!)
        networkService.downloadImage { (imageData) in
            let image = UIImage(data: imageData as Data)
            DispatchQueue.main.async(execute: {
                self.thumbnailImageView.image = image
            })
        }

        authorImageView.layer.cornerRadius = authorImageView.bounds.width / 2.0
        authorImageView.layer.masksToBounds = true
        authorImageView.layer.borderColor = UIColor.white.cgColor
        authorImageView.layer.borderWidth = 1.0
    }

    @IBOutlet weak var thumbnailImageView: UIImageView!
    @IBOutlet weak var descriptionLabel: UILabel!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var createdAtLabel: UILabel!
    @IBOutlet weak var authorImageView: UIImageView!
}

EpisodesTableViewController.swift

import UIKit
import SafariServices

class EpisodesTableViewController: UITableViewController
{
    var episodes = [Episode]()

    override func viewDidLoad()
    {
        super.viewDidLoad()

        episodes = Episode.downloadAllEpisodes()
        print(Episode.downloadAllEpisodes())
        self.tableView.reloadData()

        tableView.estimatedRowHeight = tableView.rowHeight
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle = .none            
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int
    {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {            
        return episodes.count         
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Episode Cell", for: indexPath) as! EpisodeTableViewCell
        let episode = self.episodes[(indexPath as NSIndexPath).row]

        cell.episode = episode    
        return cell
    }

    // MARK: - UITableViewDelegate

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
        IndexPath)
    {
        let selectedEpisode = self.episodes[(indexPath as NSIndexPath).row]

        // import SafariServices
        let safariVC = SFSafariViewController(url: selectedEpisode.url! as URL)
        safariVC.view.tintColor = UIColor(red: 248/255.0, green: 47/255.0, blue: 38/255.0, alpha: 1.0)
        safariVC.delegate = self
        self.present(safariVC, animated: true, completion: nil)
    }

    // MARK: - Target / Action

    @IBAction func fullBlogDidTap(_ sender: AnyObject)
    {
        // import SafariServices
        let safariVC = SFSafariViewController(url: URL(string: "http://www.ductran.io/blog")!)
        safariVC.view.tintColor = UIColor(red: 248/255.0, green: 47/255.0, blue: 38/255.0, alpha: 1.0)
        safariVC.delegate = self
        self.present(safariVC, animated: true, completion: nil)
    }        
}

extension EpisodesTableViewController : SFSafariViewControllerDelegate
{
    func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
        controller.dismiss(animated: true, completion: nil)
    }
}

whay can't show the parse json in my UITableviewCell in the app where the problem.

ArK
  • 20,698
  • 67
  • 109
  • 136

1 Answers1

0

You just need to change this downloadAllEpisodes method of Episode with closure like this.

static func downloadAllEpisodes(completion: ([Episode]) -> ()) {
    var episodes = [Episode]()
    let url = URL(string:"http://pallive.xp3.biz/DucBlog.json")
    URLSession.shared.dataTask(with: url!) { (data, response, error) in

        if error != nil {
            print(error)
            completion(episodes)
        }
        else {
            if let jsonData = data ,let jsonDictionary = NetworkService.parseJSONFromData(jsonData) {
                let espDictionaries = jsonDictionary["episodes"] as! [[String : AnyObject]]
                for espDictionary in espDictionaries {

                    let newEpisode = Episode(espDictionary: espDictionary)
                    episodes.append(newEpisode)
                }
            }
            completion(episodes)
        }

    }.resume()
}

Now call this method like this.

Episode.downloadAllEpisodes() {(episodes) -> () in
    if episodes.count > 0 {
         print(episodes)
         self.episodes = episodes
         self.tableView.reloadData()
    }
}
Nirav D
  • 71,513
  • 12
  • 161
  • 183
  • Now call this method like this. where i have other one episodes = Episode.downloadAllEpisodes() self.tableView.reloadData() tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension tableView.separatorStyle = .none } – yosri hadi Sep 12 '16 at 16:00
  • where to call in EpisodesTableViewController.swift – yosri hadi Sep 12 '16 at 16:11
  • Where you are currently calling this method call at the same place. – Nirav D Sep 12 '16 at 16:22
  • missing argument for parameter completion in call – yosri hadi Sep 12 '16 at 17:44
  • { super.viewDidLoad() episodes = Episode.downloadAllEpisodes() (episodes) -> () in if episodes.count > 0 { print(episodes) self.tableView.reloadData() } } get eroor – yosri hadi Sep 12 '16 at 17:48
  • thanks but nothing happend see image http://imgur.com/a/9Fdo8 or http://pallive.xp3.biz/a.png – yosri hadi Sep 13 '16 at 05:00
  • You need to add this line `self.episodes = episodes` before reloading tableVIew, check edited answer for more detail. – Nirav D Sep 13 '16 at 05:03
  • Welcome mate, Happy coding :) – Nirav D Sep 13 '16 at 05:08