0

I'm creating an app for my YouTube channel using the YouTube API. I'm getting the videos from a playlist using Alamofire by doing this:

let parameters = ["part":"snippet","maxResults":50,"channelId":CHANNEL_ID,"playlistId":UPLOADS_PLAYLIST_ID,"key":API_KEY] as [String : Any]

class VideoModel: NSObject {

    var videoArray = [Video]()


    func getFeedVideo() {
        Alamofire.request("https://www.googleapis.com/youtube/v3/playlistItems", parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in

            if let JSON = response.result.value {

                if let dictionary = JSON as? [String: Any] {

                    var arrayOfVideos = [Video]()

                    guard let items = dictionary["items"] as? NSArray else { return }

                    for items in dictionary["items"] as! NSArray {
                        print(items)
                        //  Create video objects off of the JSON response

                        let videoObj = Video()
                        videoObj.videoID = (items as AnyObject).value(forKeyPath: "snippet.resourceId.videoId") as! String
                        videoObj.videoTitle = (items as AnyObject).value(forKeyPath: "snippet.title") as! String
                        videoObj.videoDescription = (items as AnyObject).value(forKeyPath: "snippet.description") as! String
                        videoObj.videoThumbnailUrl = (items as AnyObject).value(forKeyPath: "snippet.thumbnails.maxres.url") as! String


                        arrayOfVideos.append(videoObj)

                    }
                    self.videoArray = arrayOfVideos
                    if self.delegate != nil {
                        self.delegate!.dataReady()
                    }
                }
            }
        }
    }

I've been searching around, and I can't find a simple way to do this. I found an answer like this one: How to get number of video views with YouTube API? But, I'm using Swift. Does anyone have any ideas?

Jacob Cavin
  • 2,169
  • 3
  • 19
  • 47
  • Possible duplicate of [How to get number of video views with YouTube API?](https://stackoverflow.com/questions/3331176/how-to-get-number-of-video-views-with-youtube-api) – PressingOnAlways Aug 04 '17 at 00:30
  • @Jacob: What's the problem ? Are you receiving the data or not ? Do you want to get video count ? Do you want to get the video ID to attach it to a Youtube Video Player ? – nathan Aug 04 '17 at 00:48
  • possible duplicate of https://stackoverflow.com/questions/3331176/how-to-get-number-of-video-views-with-youtube-api – ReyAnthonyRenacia Aug 04 '17 at 07:33
  • @nathan I'm wanting to get the views of a YouTube video. – Jacob Cavin Aug 04 '17 at 12:02

1 Answers1

0

Working solution. I'd use Decodable instead of raw JSON but I followed your code for the last request.

let apiKey = "API_KEY"
let playlistId = "PLAYLIST_ID"
let url = URL(string: "https://www.googleapis.com/youtube/v3/playlistItems?playlistId=\(playlistId)&maxResults=25&part=snippet%2CcontentDetails&key=\(apiKey)")!

// Get videos
Alamofire.request(url).responseJSON { (response) in

    guard let JSON = response.result.value,
        let dictionary = JSON as? [String: Any],
        let items = dictionary["items"] as? [AnyObject]
        else { return }

    let videos: [Video] = items.map {
        let videoObj = Video()
        videoObj.videoID = $0.value(forKeyPath: "snippet.resourceId.videoId") as! String
        videoObj.videoTitle = $0.value(forKeyPath: "snippet.title") as! String
        videoObj.videoDescription = $0.value(forKeyPath: "snippet.description") as! String
        videoObj.videoThumbnailUrl = $0.value(forKeyPath: "snippet.thumbnails.default.url") as! String
        return videoObj
    }

    let videoIds = videos.map({ $0.videoID }).joined(separator: ",")
    let statsUrl = URL(string: "https://www.googleapis.com/youtube/v3/videos?part=statistics&id=\(videoIds)&key=\(apiKey)")!

    // Get view count for all videos
    Alamofire.request(statsUrl).responseJSON { (response) in

        guard let JSON = response.result.value,
            let dictionary = JSON as? [String: Any],
            let items = dictionary["items"] as? [AnyObject]
            else { return }

        for i in 0..<items.count {
            let views = items[i].value(forKeyPath: "statistics.viewCount") as! String
            videos[i].viewCount = Int(views)!
        }

        print(videos)
    }
}
nathan
  • 9,329
  • 4
  • 37
  • 51