如何使用YouTube API V3?

11

我正在尝试在我的iOS应用程序中使用新的YouTube API(版本3),但我不知道该怎么做。 我进行了很多研究,但我发现所有的示例和代码都是针对旧版API的,因此它们无效。 到目前为止,我已经理解了,要使用新API,您必须在Google开发人员控制台中创建一个项目(我已经创建了)......但然后他们会将您发送到一个包含一些代码的页面,但我真的不知道如何使用它。链接到Google API页面 我需要知道的是如何从给定的YouTube视频URL中检索一些信息,我需要的信息是“喜欢”的总数和“观看”总数......使用API 2非常简单...但现在我真的不知道从哪里开始... 是否有人可以解释如何使用一些示例和代码来实现这一点? 我相信很多人会受益于此。

3个回答

23

您不必使用Google提供的iOS客户端来进行这些请求。

  1. 前往API控制台为您的iOS应用程序生成新的Simple API访问密钥。确保在提供的窗口中输入您应用的Bundle Identifier。或者,您可以创建一个服务器API密钥,以便通过命令行测试基本请求和curl。

  2. 找到您需要的相关终点。要查找有关视频的信息,您将需要使用Videos.list方法。

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

您将要为part参数指定一个值。从您的问题中看来,您将要传递snippetcontentDetailsstatistics值(尽管对于喜欢和观看,您只需要statistics值)。

然后传入您的视频的id(在本例中为AKiiekaEHhI,您可以添加最多50个逗号分隔的ID)和您的API密钥。您的URL应该看起来像这样:

https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id=AKiiekaEHhI&key={YOUR_API_KEY}
您也可以在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()

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];

你的日志将会看起来像这样:

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
< p > items 键对应的对象将是您在请求中传递的每个视频 ID 的信息数组。

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

if let items = jsonResult["items"] as? [AnyObject]? {
    println(items?[0]["statistics"])
}

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

{
    commentCount = 54;
    dislikeCount = 3;
    favoriteCount = 0;
    likeCount = 265;
    viewCount = 6356;
}

这种方法也可以用于实时活动。


嗨!谢谢你的回答,我使用Objective C和Xcode进行编程,明天我会尝试在我的项目中使用你提供的信息,并告诉你结果。感谢你的帮助。 - Blue
@Blue 你应该真的更改你问题的标签。iOS != Objective-C,而Xcode使用Objective-C和Swift两种语言。尽管如此,我已经添加了一个Objective-C实现,并请求编辑你的问题以包括Objective-C标签。 - JAL
非常感谢你,兄弟,现在它可以工作了...我只是不明白如何设置iOS API访问...在哪里和如何设置...无论如何,非常感谢你的帮助...我会给你赏金... - Blue
很高兴能够帮助,愉快地编程吧! - JAL
1
@ThiG. 我是通过阅读文档学会这些知识的。我认为 Google 没有提供任何 Swift 特定的示例,所以我只是在调用他们的 REST API。 - JAL
显示剩余14条评论

7

// Swift 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()









}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接