How to use YouTube API V3?
You don't have to use the iOS client Google provides to make those kinds of request.
Navigate to the API Console and generate a new Simple API Access key for your iOS application. Be sure to enter your app's bundle identifier in the provided window. Alternatively, you can create a Server API key for testing with basic requests and curl from the command line.
Find the relevant endpoint for your needs. To find information about a video, you'll want to use the Videos.list method.
First, set up you URL. I will be using this URL as an example: https://www.youtube.com/watch?v=AKiiekaEHhI
You're going to want to specify a value for the part
parameter. From your question, it looks like you're going to want to pass in the snippet
, contentDetails
, and statistics
values (although for likes and views, you really only need the statistics
value).
Then pass in the id
of your video (in this case AKiiekaEHhI
, you can add up to 50 comma-separated IDs) and your API key. Your URL should look something like this :
https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id=AKiiekaEHhI&key={YOUR_API_KEY}
You can also do this in the API Explorer.
Swift implementation:
// 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 implementation:
(This post has been edited to support NSURLSession
. For an implementation that uses NSURLConnection
, check the edit history)
// 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];
Your log will look something like this:
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
The object for the items
key will be an array of info for each video id you passed in to the request.
By digging into this response, you will be able to get the information you need. For example:
if let items = jsonResult["items"] as? [AnyObject]? {
println(items?[0]["statistics"])
}
Will give you a dictionary of the video's statistics (where you can get the number of likes and the number of views).
{
commentCount = 54;
dislikeCount = 3;
favoriteCount = 0;
likeCount = 265;
viewCount = 6356;
}
This same approach can be used with live events.
Youtube Data Api v3
Once you have your Youtube Data API v3 key then use Videos: list endpoint this way: https://www.googleapis.com/youtube/v3/videos?part=snippet&id=YOUR_VIDEO_ID&key=YOUR_API_KEY then in the answer the fields title
and thumbnails
are what you are looking for.
How to use YouTube Data API v3 to search video duration with Search endpoint not Videos endpoint?
Unfortunately, want you want to achieve is not possible: the Search.list
API endpoint does not return a video's duration
property.
This behavior is in accordance with the official specs: the response of Search.list
has its items
property made of search resource objects. These objects does not provide much details about the respective API resources -- videos, channels or playlists.
When you obtain, upon a Search.list
invocation, a list of video IDs, you may well ask the Videos.list
API endpoint to provide any metadata pertaining to those videos -- including the duration
property.
Do note that the Videos.list
endpoint accepts its request parameter id
to be a comma-separated list of at most 50 video IDs. Also note that (irrespective of the number of actual IDs passed on to id
) the quota cost of one call to Videos.list
is 1 unit (very cheap).
use YouTube Data API (v3) to update a video via API keys got a 401 error
According to the official doc you yourself quoted, for to invoke the Videos.update
API endpoint, you need to be properly authorized:
Authorization
This request requires authorization with at least one of the following scopes (read more about authentication and authorization).
Scope
https://www.googleapis.com/auth/youtubepartner
https://www.googleapis.com/auth/youtube
https://www.googleapis.com/auth/youtube.force-ssl
Consequently, there's no way you can avoid using OAuth 2.0 authentication/authorization flow within you app. Note that API keys are used and useful for reading-only public data.
For the part of your question that says:
[...] it is impossible to open a browser window and make the user to do a oauth login and authorization in a quartz job [...]
the API has solutions. Do read the following two docs: OAuth 2.0 for Mobile & Desktop Apps and Using OAuth 2.0 for Web Server Applications.
A brief, top-level description of what you'll have to do is provided by the answer I gave recently to a similar question. That answer may help you understand more easily the way to attain a solution to your problem.
Related Topics
Error Appstore Connect:Missing Purpose String in Info.Plist File
iOS Alamofire Stop All Requests
Add Nsurlconnection Loading Process on Uiprogressview
Avaudioplayer Produces Lag Despite Preparetoplay() in Swift
iOS - How to Make an Animation Track Touches
The Identity Used to Sign the Executable Is No Longer Valid
How to Determine Device Type from Swift? (Os X or iOS)
How to Stop Firebase from Logging Status Updates When App Is Launched
Ios7 Safari: Saving to Home-Screen and Persist Token
How to Use Avsamplebufferdisplaylayer in iOS 8 for Rtp H264 Streams with Gstreamer
How to Disable Caching from Nsurlsessiontask
Differencebetween a Development Provisioning Profile and an Ad Hoc Provisioning Profile
Text Color Based on Background Image
Sudzc Arc Version - Objc_Msgsend Call Causes Exc_Bad_Access Using 64-Bit Architecture
Issue with Auto Layout on iOS 8 (Code Works Perfectly on iOS 7)
How to Stop Uitableview from Clipping Uitableviewcell Contents in iOS 7
Uitextfield Should Accept Number Only Values
Why Does Safari Mobile Have Trouble Handling Many Input Fields on iOS 8