Я не могу получить доступ к значениям в ответе json Swift 4 - PullRequest
0 голосов
/ 04 января 2019

Я пытаюсь использовать API YouTube для отображения всех видео из определенного канала 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
                }
            }
        }
    }
}

Вот вывод консоли:

* * 1006 Video.self = VideoInfo (пункты: [Fawx_Music_App.VideoInfo.Items (ID: "VVU3d1p3dEFLMVRZbUZTa05CejNFXzNBLjBHUzYxTDFDTWZV", фрагмент кода: Fawx_Music_App.VideoInfo.Snippet (ResourceId: Fawx_Music_App.VideoInfo.ResourceId (VideoID: "0GS61L1CMfU"), эскизы: Fawx_Music_App.VideoInfo.Thumbnails (высокая: Fawx_Music_App.VideoInfo.High (URL: «https://i.ytimg.com/vi/0GS61L1CMfU/hqdefault.jpg")), название: "FAWX- Мощный")), Fawx_Music_App.VideoInfo.Items (идентификатор: "VVU3d1p3dEFLMVRZbUZTa05CejNFXzNBLmh1Rng2MVdQZnNj", фрагмент кода: Fawx_Music_App.VideoInfo.Snippet (resourceId: Fawx_Music_App.VideoInfo.ResourceId (videoId: "huFx61WPfsc"), миниатюры: Fawx_Music_App.VideoInfo.Thumbnails (высокая: Fawx_Music_App.VideoInl0 * * 0 * * 0Национальная армия

1 Ответ

0 голосов
/ 04 января 2019

пожалуйста, попробуйте:

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