我无法访问json响应Swift 4中的值

时间:2019-01-04 04:03:02

标签: json swift4 youtube-data-api codable

我正在尝试使用youtube api将来自特定youtube频道的所有视频显示到tableViewController上。打印结果时,我在控制台中收到了我需要的所有信息,但是我无法弄清楚如何访问结果中的值。

import UIKit

struct VideoInfo : Codable {

    struct First : Codable {
        let kind: String
    }

    struct Items : Codable {
        let id: String

        let snippet: Snippet
    }

    struct Snippet: Codable {
        //let title: String?
        let resourceId: ResourceId
        let thumbnails: Thumbnails
        let title: String

      enum CodingKeys: String, CodingKey {
           case title
           case resourceId
           case thumbnails
        }
    }

    struct Thumbnails: Codable {
        let high: High
    }

    struct High: Codable {
        let url: String

        enum CodingKeys: String, CodingKey {
            case url
        }
    }

    struct ResourceId : Codable {
        let videoId: String

        enum CodingKeys: String, CodingKey {
            case videoId
        }
    }
    let items: [Items]

}



class FirstView: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var fawxData = [FawxData]()

    @IBAction func topSongsPressed(_ sender: Any) {
        print("title.rawvalue \(VideoInfo.Snippet.CodingKeys.title.rawValue)")
    }

    @IBOutlet weak var tableView: UITableView!

    let urlTest = "<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/huFx61WPfsc\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>"

    override func viewDidLoad() {
        super.viewDidLoad()

        let fA1 = FawxData(imageUrl: "https://img.youtube.com/vi/huFx61WPfsc/hqdefault.jpg", videoURL: "huFx61WPfsc", videoTitle: "Seven Nation Army Cover")
        let fA2 = FawxData(imageUrl: "https://img.youtube.com/vi/0GS61L1CMfU/hqdefault.jpg", videoURL: "0GS61L1CMfU", videoTitle: "Powerful")
        let fA3 = FawxData(imageUrl: "https://img.youtube.com/vi/Eyzov4pdap8/hqdefault.jpg", videoURL: "Eyzov4pdap8", videoTitle: "Trees")
       // let fA4 = FawxData(imageUrl: VideoInfo.High.CodingKeys.url.rawValue, videoURL: VideoInfo.ResourceId.CodingKeys.videoId.rawValue, videoTitle: VideoInfo.Snippet.CodingKeys.title.rawValue)
        fawxData.append(fA1)
        fawxData.append(fA2)
        fawxData.append(fA3)
        //fawxData.append(fA4)
        tableView.delegate = self
        tableView.dataSource = self
        print(fawxData.count)

        let youtubeApi = "https://www.googleapis.com/youtube/v3/playlistItems?playlistId=UU7wZwtAK1TYmFSkNBz3E_3A&key=**********************&part=snippet&maxResults=50"
        guard let url = URL(string: youtubeApi) else
            {return}

        // Creating request
        URLSession.shared.dataTask(with: url) { (data, response, error) in

            guard let data = data else {return}
            do {
                let videoInfo = try JSONDecoder().decode(VideoInfo.self, from: data)
                print("Video.self = \(videoInfo.self)")


            }
            catch {
                print("json error: \(error)")
            }

        }
        .resume()
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if let cell = tableView.dequeueReusableCell(withIdentifier: "fawxCell", for: indexPath) as? FawxCell{
        let selectedInfo = fawxData[indexPath.row]

        cell.updateUI(fawxData: selectedInfo)
            tableView.rowHeight = 100
            return cell
        }else{
            return UITableViewCell()
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let videoInfo = fawxData[indexPath.row]
        performSegue(withIdentifier: "PlayVideo", sender: videoInfo)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?){
        if segue.identifier == "PlayVideo"{
            if tableView.indexPathForSelectedRow != nil{
                if let navigationContoller = segue.destination as? VideoVC{
                    let destVC = navigationContoller
                    //Getting selected videoInfo
                    let myIndexPath = self.tableView.indexPathForSelectedRow!
                    let row = myIndexPath.row
                    //Passing selected video to detail view
                    destVC.videoPassed = fawxData[row].videoUrl
                }
            }
        }
    }
}

这是控制台输出:

  

Video.self = VideoInfo(项目:[Fawx_Music_App.VideoInfo.Items(id:“ VVU3d1p3dEFLMVRZbUZTa05CejNFXzNBLjBHUzYxTDFDFDTWZV”,代码段:Fawx_Music_App.VideoInfo_S:Fusx_Fusx:Fawx_Music_App.VideoInfo_S:(1。 .VideoInfo.Thumbnails(high:Fawx_Music_App.VideoInfo.High(url:“ https://i.ytimg.com/vi/0GS61L1CMfU/hqdefault.jpg”)),标题:“ FAWX- Powerful”)),Fawx_Music_App.VideoInfo.Items(id:“ VVU3d1p3dEFLMVRZbUZTa05CejNFXMus,” .VideoInfo.Snippet(resourceId:Fawx_Music_App.VideoInfo.ResourceId(videoId:“ huFx61WPfsc”),缩略图:Fawx_Music_App.VideoInfo.Thumbnails(高:Fawx_Music_App.VideoInfo.High(URL:“ https://i.ytimg.com/vi/huFx61WPfsc/hqdefault.jpg”)),标题: “ FAWX音乐七国军

1 个答案:

答案 0 :(得分:1)

请尝试:

URLSession.shared.dataTask(with: url) { [weak self] (data, response, error) in
....

    self?.fawxData.removeAll() //if loadmore just remove this method
    let displayData = videoInfo.items.map ({
         FawxData(imageUrl: $0.snippet.resourceId.thumbnails.high.url, videoURL: $0.snippet.resourceId.videoId, videoTitle: $0.snippet.resourceId.thumbnails.high.title)
    })
    self?.fawxData.append(contentsOf: displayData)
    self?.tableView.reloadData()
....