简体   繁体   English

来自URL的Swift 3 json无法获取单元uitableview

[英]swift 3 json from url can't get cell uitableview

swift 3 json from url can't problem to get cell uitableview 从URL迅速3 json不能问题以获取单元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 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 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. 为什么无法在问题所在的应用程序的UITableviewCell中显示解析的json。

You just need to change this downloadAllEpisodes method of Episode with closure like this. 您只需要使用关闭方法来更改Episode downloadAllEpisodes方法即可。

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()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM