来自 url 的 swift 3 json 无法获取单元格 uitableview

Posted

技术标签:

【中文标题】来自 url 的 swift 3 json 无法获取单元格 uitableview【英文标题】:swift 3 json from url can't get cell uitableview 【发布时间】:2016-09-12 15:16:05 【问题描述】:

来自 url 的 swift 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

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)
    

为什么无法在应用程序中的我的UITableviewCell 中显示解析 json 问题出在哪里。

【问题讨论】:

episodes.count 的输出是什么? 您填充episodes 数组的方式是错误的。见:***.com/questions/25203556/… 这个方法需要使用闭包downloadAllEpisodes 你能帮我做吗,谢谢 任何人都可以制作这个 Episode.swift 【参考方案1】:

你只需要改变这个EpisodedownloadAllEpisodes方法,像这样关闭。

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

现在像这样调用这个方法。

Episode.downloadAllEpisodes() (episodes) -> () in
    if episodes.count > 0 
         print(episodes)
         self.episodes = episodes
         self.tableView.reloadData()
    

【讨论】:

现在像这样调用这个方法。我还有其他一集 = Episode.downloadAllEpisodes() self.tableView.reloadData() tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension tableView.separatorStyle = .none 在 EpisodesTableViewController.swift 中调用的位置 你当前调用这个方法的地方在同一个地方调用。 调用中的参数完成缺少参数 super.viewDidLoad() episodes = Episode.downloadAllEpisodes() (episodes) -> () in if episodes.count > 0 print(episodes) self.tableView.reloadData() get埃罗

以上是关于来自 url 的 swift 3 json 无法获取单元格 uitableview的主要内容,如果未能解决你的问题,请参考以下文章

无法在swift 3中解析Json?

无法使用 Swift 将图像 url 从 JSON(API) 绑定到 tableviewcell

无法将 JSON 数据解析为 Swift

使用 Swift 3 和 Alamofire 在 JSON url 中的应用程序中没有显示任何内容

如何使用来自 3rd 方站点的 URL 端点进行 JSON 响应

如何解析这个 JSON 口袋妖怪字典?口袋妖怪 API (swift 3)