LoginSignup
159
158

More than 5 years have passed since last update.

YouTubeの動画情報をData API v3を使って取得する

Last updated at Posted at 2014-11-11

YouTubeの動画情報はData APIからJSON形式で取得することができます。
iOSのアプリ内で取得した情報をそれぞれクラス内の変数に確保してみます。

今回は、動画のタイトル、チャンネル名、サムネイル画像のURLを取得してみています。

準備

Data API v3を使う前に、予めGoogle Developers Consoleでプロジェクトの登録をしておく必要があります。

アカウントの登録後、プロジェクトを作成して「YouTUbe Data API v3」を有効にした後、APIs & auth → CredentialsからCreate new Keyを選択してアクセスを許可するためのキーを作成します。

Create new Keyを押すと作成するキーの種類(Server, Browser, Android, iOS)を確認されるので、iOS用のものを作成しておきます。また、テストのため、Browser用も作成しておきます。

スクリーンショット 2014-11-11 16.25.59.png

発行されるキーを後ほどコードに埋め込みます。
iOSのアプリはbundleID、BrowserはURLでアクセスを許可するアプリケーションを制限することもできます。

APIを叩いてみる

さっそく叩いてみます。ブラウザで下記のURLを入力します。
myKeyのところには、さきほど登録したBrowser Keyを入れてください。

下の例は、livetuneさんのtell your worldの動画情報を取得する例です。

https://www.googleapis.com/youtube/v3/videos?id=PqJNc9KVIZE&key=【myKey】&fields=items(id,snippet(channelTitle,title,thumbnails),statistics)&part=snippet,contentDetails,statistics

このような結果が返ってきます。

result
{
 "items": [
  {
   "id": "PqJNc9KVIZE",
   "snippet": {
    "title": "livetune feat. 初音ミク 『Tell Your World』Music Video",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/PqJNc9KVIZE/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/PqJNc9KVIZE/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/PqJNc9KVIZE/hqdefault.jpg",
      "width": 480,
      "height": 360
     },
     "standard": {
      "url": "https://i.ytimg.com/vi/PqJNc9KVIZE/sddefault.jpg",
      "width": 640,
      "height": 480
     },
     "maxres": {
      "url": "https://i.ytimg.com/vi/PqJNc9KVIZE/maxresdefault.jpg",
      "width": 1280,
      "height": 720
     }
    },
    "channelTitle": "kzlivetune"
   },
   "statistics": {
    "viewCount": "10196463",
    "likeCount": "52993",
    "dislikeCount": "1355",
    "favoriteCount": "0",
    "commentCount": "21495"
   }
  }
 ]
}

VideoIDはYouTube動画のURLのhttps://www.youtube.com/watch?v=【hogehoge】
の【hogehoge】に当たる部分です。ここを変更すれば任意の動画情報を取得できます。

https://www.googleapis.com/youtube/v3/videos?id=【hogehoge】&key=【myKey】&fields=items(id,snippet(channelTitle,title,thumbnails),statistics)&part=snippet,contentDetails,statistics

iOSアプリで取得してJSONを展開する

基本的にはブラウザと同じなので、リクエスト送信とJSON展開の部分を書き加えます。

getVideoInofo.swift
import Foundation
import UIKit

public class VideoItem {

    var videoId: NSString = "hogehoge"
    var myKey: NSString = "hugahuga"
    var title: NSString = NSString()
    var creator: NSString = NSString()
    var imageUrl: NSString = NSString()

    func setYouTubeVideoInformation() {
        if (Util.hasConnectivity()) { // ネットワーク接続を確認
            var apiUrl: NSString = "https://www.googleapis.com/youtube/v3/videos?id=\(self.videoId)&key=\(self.myKey)&fields=items(id,snippet(channelTitle,title,thumbnails),statistics)&part=snippet,contentDetails,statistics"

            // create request object
            var requestUrl: NSURL = NSURL(string: apiUrl)!
            var request: NSURLRequest = NSURLRequest(URL: requestUrl)

            // request to api
            var data: NSData =  NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: NSErrorPointer())!

            // read json response
            let json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as NSDictionary
            let itemsArray: NSArray = json.objectForKey("items") as NSArray
            let items: NSDictionary = itemsArray[0] as NSDictionary
            let snippet: NSDictionary = items.objectForKey("snippet") as NSDictionary

            // title
            let title: NSString = snippet.objectForKey("title") as NSString
            self.title = title

            // channel title
            let channelTitle: NSString = snippet.objectForKey("channelTitle") as NSString
            self.creator = channelTitle

            // thumbnail image
            let thumbnails: NSDictionary = snippet.objectForKey("thumbnails") as NSDictionary
            let resolution: NSDictionary = thumbnails.objectForKey("high") as NSDictionary
            let imageUrl: NSString = resolution.objectForKey("url") as NSString

            self.imageUrl = imageUrl
        }
    }
}

JSONの展開はひとつずつNSArrayかNSDictionaryに展開しています。
なんだかスマートじゃないですね。もっと上手く書く方法はないものか…。
どちらで展開するかも間違えると問答無用で落ちてしまうので要対応かもしれません。

おまけ - UIImageに取得した画像URLの画像を入れる

APIからはサムネイル画像のURLしか取れないので、これを使って実際にUIImageにサムネイル画像を入れてみます。
一行だけですが、こんな感じです。

setImage.swift
var image: UIImage? = UIImage(data: NSData(contentsOfURL: NSURL(string: imageUrl)!)!)

画像の読み込み中は他の処理が止まって見えるので、並列処理させるのがよさそうです。

159
158
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
159
158