How to format the duration returned from youtube api v3 reuqest using objective-c?
You can use the following code:
- (NSString *)parseDuration:(NSString *)duration {
NSInteger hours = 0;
NSInteger minutes = 0;
NSInteger seconds = 0;
NSRange timeRange = [duration rangeOfString:@"T"];
duration = [duration substringFromIndex:timeRange.location];
while (duration.length > 1) {
duration = [duration substringFromIndex:1];
NSScanner *scanner = [NSScanner.alloc initWithString:duration];
NSString *part = [NSString.alloc init];
[scanner scanCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&part];
NSRange partRange = [duration rangeOfString:part];
duration = [duration substringFromIndex:partRange.location + partRange.length];
NSString *timeUnit = [duration substringToIndex:1];
if ([timeUnit isEqualToString:@"H"])
hours = [part integerValue];
else if ([timeUnit isEqualToString:@"M"])
minutes = [part integerValue];
else if ([timeUnit isEqualToString:@"S"])
seconds = [part integerValue];
}
return [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
You can also read up on ISO_8601 durations here.
How to get content details in YouTube Search API v3 ? (Swift)
The search API v3 does not have the duration in the search API , you need use the video API to get the video information.
var urlString = "https://www.googleapis.com/youtube/v3/videos?key=\(apiKey)&part=contentDetails&id="
Use this URL and then add in the id behind like this U4_Os5LNVjg, s23mnsidmm for multiple ID and then use this to convert the duration format from YouTube
How to Convert duration form youtube api in swift?
How do I get video durations with YouTube API version 3?
You will have to make a call to the YouTube data API's video resource after you make the search call. You can put up to 50 video IDs in a search, so you won't have to call it for each element.
https://developers.google.com/youtube/v3/docs/videos/list
You'll want to set part=contentDetails
, because the duration is there.
For example, the following call:
https://www.googleapis.com/youtube/v3/videos?id=9bZkp7q19f0&part=contentDetails&key={YOUR_API_KEY}
Gives this result:
{
"kind": "youtube#videoListResponse",
"etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/ny1S4th-ku477VARrY_U4tIqcTw\"",
"items": [
{
"id": "9bZkp7q19f0",
"kind": "youtube#video",
"etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/HN8ILnw-DBXyCcTsc7JG0z51BGg\"",
"contentDetails": {
"duration": "PT4M13S",
"dimension": "2d",
"definition": "hd",
"caption": "false",
"licensedContent": true,
"regionRestriction": {
"blocked": [
"DE"
]
}
}
}
]
}
The time is formatted as an ISO 8601 string. PT stands for Time Duration, 4M is 4 minutes, and 13S is 13 seconds.
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.
Convert youtube Api v3 video duration in php
Using DateTime class
You could use PHP's DateTime class to achieve this. This solution is much simpler, and will work even if the format of the quantities in the string are in different order. A regex solution will (most likely) break in such cases.
In PHP, PT2H34M25S
is a valid date period string, and is understood by the DateTime parser. We then make use of this fact, and just add it to the Unix epoch using add()
method. Then you can format the resulting date to obtain the required results:
function covtime($youtube_time){
if($youtube_time) {
$start = new DateTime('@0'); // Unix epoch
$start->add(new DateInterval($youtube_time));
$youtube_time = $start->format('H:i:s');
}
return $youtube_time;
}
echo covtime('PT2H34M25S');
Demo
Related Topics
Ruby: Loaderror - Library Not Found for Class Digest::Sha1 -- Digest/Sha1
Uibezierpath Subclass Initializer
How to Work with Udp Sockets in iOS, Swift
Screen Recording When My iOS App Is in Background with Replaykit
Target Is Not Found, Please Reconnect the Device, Xcode:Device Support File
iOS - Setobject VS. Synchronize
How to Update iOS 14 Widget Background Color from the App
iOS App Crashes on Phone But Works Fine on Simulator
How to Add Followed Text to Uitextfield
How to Load Thousands Records to Realm Correctly
Pure Swiftui Login, Signup, Register Flow, Is It Possible
Swift 3 - Passing Data Between a View Controller and After That to Another 2
Outline Uilabel Text in Uilabel Subclass
iOS Uiimagepickercontroller: Any Way of Getting the Date of the Chosen Picture
Swift iOS Record Video and Audio with Avfoundation
Checkbox Uitableview with Different Sections
Swift Computed Properties Cannot Be Used in Init
Binary Operator + Cannot Be Applied to Operands of Type Cgfloat Int