如何使用YouTube API V3?

Blu*_*lue 10 objective-c youtube-api ios swift youtube-livestreaming-api

我正在尝试弄清楚如何在我的iOS应用中使用新的YouTube API(第3版),但我不知道该怎么做.我做了很多关于它的研究,但我发现的是旧API的所有示例和代码,因此它们无效.现在我明白了,为了使用新的API,您必须在Google Developer Console中创建一个项目(我做到了)...但是他们会将您发送到一个包含一些代码的页面,但我真的不明白如何使用它.链接到谷歌api页面 我需要知道的是如何从YouTube视频的给定URL中检索一些信息,我需要的信息是"喜欢"的总数和"视图"的总数...使用API​​ 2它这样做很简单......但是现在我真的不知道从哪里开始......有没有人可以用一些例子和一些代码来解释如何实现这个目标?我很确定很多人会从中受益.

JAL*_*JAL 22

您不必使用Google提供的iOS客户端来提出这类请求.

  1. 导航到API控制台并为您的iOS应用程序生成新的Simple API Access密钥.请务必在提供的窗口中输入应用程序的包标识符.或者,您可以创建服务器API密钥,以便使用命令行中的基本请求和卷曲进行测试.

  2. 根据您的需求查找相关端点.要查找有关视频的信息,您需要使用Videos.list方法.

首先,设置您的URL.我将使用此网址作为示例:https://www.youtube.com/watch?v = AKiiekaEHhI

您将要为part参数指定值.从你的问题,它看起来像你会想在传递snippet,contentDetailsstatistics值(虽然喜欢和看法,你真的只需要statistics值).

然后传入id您的视频(在这种情况下AKiiekaEHhI,您最多可以添加50个以逗号分隔的ID)和您的API密钥.您的网址应如下所示:

https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id=AKiiekaEHhI&key={YOUR_API_KEY}
Run Code Online (Sandbox Code Playgroud)

您也可以在API Explorer中执行此操作.

Swift实现:

// Set up your URL
let youtubeApi = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id=AKiiekaEHhI&key={YOUR_API_KEY}"
let url = NSURL(string: youtubeApi)

// Create your request
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
    do {
        if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? [String : AnyObject] {

            print("Response from YouTube: \(jsonResult)")
        }
    }
    catch {
        print("json error: \(error)")
    }

})

// Start the request
task.resume()
Run Code Online (Sandbox Code Playgroud)

Objective-C实施:

(此帖子已经过编辑以支持NSURLSession.对于使用的实现NSURLConnection,请检查编辑历史记录)

// Set up your URL
NSString *youtubeApi = @"https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id=AKiiekaEHhI&key={YOUR_API_KEY}";
NSURL *url = [[NSURL alloc] initWithString:youtubeApi];

// Create your request
NSURLRequest *request = [NSURLRequest requestWithURL:url];

// Send the request asynchronously
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *connectionError) {

    // Callback, parse the data and check for errors
    if (data && !connectionError) {
        NSError *jsonError;
        NSDictionary *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];

        if (!jsonError) {
            NSLog(@"Response from YouTube: %@", jsonResult);
        }
    }
}] resume];
Run Code Online (Sandbox Code Playgroud)

您的日志将如下所示:

Response from YouTube: {
    etag = "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/AAjIATmVK_8ySsAWwEuNfdZdjW4\"";
    items =     (
                {
            contentDetails =             {
                caption = false;
                definition = hd;
                dimension = 2d;
                duration = PT17M30S;
                licensedContent = 1;
            };
            etag = "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/8v8ee5uPZQa1-ucVdjBdAVXzcZk\"";
            id = AKiiekaEHhI;
            kind = "youtube#video";
            snippet =             {
                categoryId = 20;
                channelId = UCkvdZX3SVgfDW8ghtP1L2Ug;
                channelTitle = "Swordless Link";
                description = "Follow me on Twitter! http://twitter.com/swordlesslink\n\nFollow me on TwitchTV for live video game streaming! http://twitch.tv/swordlesslink";
                liveBroadcastContent = none;
                localized =                 {
                    description = "Follow me on Twitter! http://twitter.com/swordlesslink\n\nFollow me on TwitchTV for live video game streaming! http://twitch.tv/swordlesslink";
                    title = "The Legend of Zelda: Majora's Mask With Glitches - Part 17: Going Against the Flow";
                };
                publishedAt = "2015-05-04T10:01:43.000Z";
                thumbnails =                 {
                    default =                     {
                        height = 90;
                        url = "https://i.ytimg.com/vi/AKiiekaEHhI/default.jpg";
                        width = 120;
                    };
                    high =                     {
                        height = 360;
                        url = "https://i.ytimg.com/vi/AKiiekaEHhI/hqdefault.jpg";
                        width = 480;
                    };
                    medium =                     {
                        height = 180;
                        url = "https://i.ytimg.com/vi/AKiiekaEHhI/mqdefault.jpg";
                        width = 320;
                    };
                    standard =                     {
                        height = 480;
                        url = "https://i.ytimg.com/vi/AKiiekaEHhI/sddefault.jpg";
                        width = 640;
                    };
                };
                title = "The Legend of Zelda: Majora's Mask With Glitches - Part 17: Going Against the Flow";
            };
            statistics =             {
                commentCount = 54;
                dislikeCount = 3;
                favoriteCount = 0;
                likeCount = 265;
                viewCount = 6356;
            };
        }
    );
    kind = "youtube#videoListResponse";
    pageInfo =     {
        resultsPerPage = 1;
        totalResults = 1;
    };
} with error: nil
Run Code Online (Sandbox Code Playgroud)

items密钥的对象将是您传递给请求的每个视频ID的信息数组.

通过深入了解此响应,您将能够获得所需的信息.例如:

if let items = jsonResult["items"] as? [AnyObject]? {
    println(items?[0]["statistics"])
}
Run Code Online (Sandbox Code Playgroud)

将为您提供视频统计数据的字典(您可以在其中获取喜欢的数量和观看次数).

{
    commentCount = 54;
    dislikeCount = 3;
    favoriteCount = 0;
    likeCount = 265;
    viewCount = 6356;
}
Run Code Online (Sandbox Code Playgroud)

这种方法可以与直播活动一起使用.


小智 6

// 斯威夫特 3

func search() {


   let videoType = "video you want to search"

    // can use any text


    var dataArray = [[String: AnyObject]]()
    // store videoid , thumbnial , Title , Description

    var apiKey = "_________________"

     // create api key from google developer console for youtube



        var urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=\(videoType)&type=video&videoSyndicated=true&chart=mostPopular&maxResults=10&safeSearch=strict&order=relevance&order=viewCount&type=video&relevanceLanguage=en&regionCode=GB&key=\(apiKey)"



        urlString = urlString.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)!
        let targetURL = URL(string: urlString)

        let config = URLSessionConfiguration.default // Session Configuration
        let session = URLSession(configuration: config)

        let task = session.dataTask(with: targetURL!) {

            data, response, error in


            if error != nil {

                print(error!.localizedDescription)


                var alert = UIAlertView(title: "alert", message: "No data.", delegate: nil, cancelButtonTitle: "OK")
                alert.show()



                return

            }

            else {




                do {





                    typealias JSONObject = [String:AnyObject]

                    let  json = try JSONSerialization.jsonObject(with: data!, options: []) as! JSONObject
                    let items  = json["items"] as! Array<JSONObject>



                    for i in 0 ..< items.count {

                        let snippetDictionary = items[i]["snippet"] as! JSONObject
                        print(snippetDictionary)
                        // Initialize a new dictionary and store the data of interest.
                        var youVideoDict = JSONObject()

                        youVideoDict["title"] = snippetDictionary["title"]
                        youVideoDict["channelTitle"] = snippetDictionary["channelTitle"]
                        youVideoDict["thumbnail"] = ((snippetDictionary["thumbnails"] as! JSONObject)["high"] as! JSONObject)["url"]
                        youVideoDict["videoID"] = (items[i]["id"] as! JSONObject)["videoId"]






                        dataArray.append(youVideoDict)


                       print(dataArray)



                        // video like can get by videoID.




                    }


                }

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

            }
        }
        task.resume()









}
Run Code Online (Sandbox Code Playgroud)