Retrieve YouTube channel videos by channel name - ios

I am looking for two API calls in Youtube Data API V3.
First I want to get the Channel ID by specifying the name of the channel.
Once I have the Channel ID I want to get n number of videos from that channel.
I am looking for the API calls that I have to make.
Also, does anyone know if there's a chance that channel or video IDs may change at some point? If they can change for the same video/channel then I should not hardcode the ID's in my code.
Thanks

For total newbies who want a running example : consider a function that will help understand the entire cycle of fetch,parse,display etc and bring youtube channel's videos to your tableview specifically. im not writing the tableview part here
-(void)initiateRequestToYoutubeApiAndGetChannelInfo
{
NSString * urlYouCanUseAsSample = #"https://www.googleapis.com/youtube/v3/search?key={YOUR_API_KEY_WITHOUT_CURLY_BRACES}&channelId={CHANNEL_ID_YOU_CAN_GET_FROM_ADDRESS_BAR_WITHOUT_CURLY_BRACES}&part=snippet,id&order=date&maxResults=20";
NSURL *url = [[NSURL alloc] initWithString: urlYouCanUseAsSample];
// Create your request
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// Send the request asynchronously remember to reload tableview on global thread
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, 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) {
// better put a breakpoint here to see what is the result and how it is brought to you. Channel id name etc info should be there
NSLog(#"%#",jsonResult);
/// separating "items" dictionary and making array
//
id keyValuePairDict = jsonResult;
NSMutableArray * itemList = keyValuePairDict[#"items"];
for (int i = 0; i< itemList.count; i++) {
/// separating VIDEO ID dictionary from items dictionary and string video id
id v_id0 = itemList[i];
NSDictionary * vid_id = v_id0[#"id"];
id v_id = vid_id;
NSString * video_ID = v_id[#"videoId"];
//you can fill your local array for video ids at this point
// [video_IDS addObject:video_ID];
/// separating snippet dictionary from itemlist array
id snippet = itemList[i];
NSDictionary * snip = snippet[#"snippet"];
/// separating TITLE and DESCRIPTION from snippet dictionary
id title = snip;
NSString * title_For_Video = title[#"title"];
NSString * desc_For_Video = title[#"description"];
//you can fill your local array for titles & desc at this point
// [video_titles addObject:title_For_Video];
// [video_description addObject:desc_For_Video];
/// separating thumbnail dictionary from snippet dictionary
id tnail = snip;
NSDictionary * thumbnail_ = tnail[#"thumbnails"];
/// separating highresolution url dictionary from thumbnail dictionary
id highRes = thumbnail_;
NSDictionary * high_res = highRes[#"high"];
/// separating HIGH RES THUMBNAIL IMG URL from high res dictionary
id url_for_tnail = high_res;
NSString * thumbnail_url = url_for_tnail[#"url"];
//you can fill your local array for titles & desc at this point
[video_thumbnail_url addObject:thumbnail_url];
}
// reload your tableview on main thread
//[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
performSelectorOnMainThread:#selector(reloadInputViews) withObject:nil waitUntilDone:NO];
// you can log all local arrays for convenience
// NSLog(#"%#",video_IDS);
// NSLog(#"%#",video_titles);
// NSLog(#"%#",video_description);
// NSLog(#"%#",video_thumbnail_url);
}
else
{
NSLog(#"an error occurred");
}
}
}];
}

First call is a search.list with setting q as channel name and type="channel".
Second one is calling channels.list with that id and get the playlistId of the uploaded videos list.
Third is the playlistItems.list to list videos under that playlist.

Related

Load Random APi Content

How do I change this function to load content randomly from the API? I want to pass in a random integer and change the end point of the url.
NSString* WebServiceURL =#"http://movie-quotes.herokuapp.com/api/v1/quotes";
to this
http://movie-quotes.herokuapp.com/api/v1/quotes/2
where the number at the end is the quote number
Here is my relevant code:
-(void)LoadQuotesRandom
{
randomQuotes = nil;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
// Load the JSON string from our web serivce (in a background thread)
NSDictionary * dictionary = [JSONHelper loadJSONDataFromURL:WebServiceURL];
dispatch_async(dispatch_get_main_queue(), ^{
randomQuotes = [NSMutableArray array];
// Iterate through the array of Customer records in the dictionary
for (NSDictionary * oneQuote in dictionary)
{
Quotes* newQuotes =[[Quotes alloc] init];
// Add our new Customer record to our NSMutableArray
newQuotes.Quote = [oneQuote objectForKey:#"content"];
newQuotes.FilmName =[oneQuote objectForKey:#"film"];
[randomQuotes addObject:newQuotes];
}
});
});
}
To restate more simply, I think you want a url string with a random integer suffix.
NSInteger randomInt = arc4random_uniform(SOME_MAX);
NSString *baseUrl = #"http://movie-quotes.herokuapp.com/api/v1/quotes";
NSString *webServiceUrl = [NSString stringWithFormat:#"%#/%ld", baseUrl, randomInt];
You'll need to #define SOME_MAX for the largest quote index one can request.
I suggest you separate this completely for the code that makes the request. Get one piece working that does any request given a string describing the url, and a separate piece that generates these url strings.

Display all JSON data from NSDictionary to UITableview

I am fairly new to iOS development, been at it for 2 years or so. I have developed an app for my Litecoin mining pool that is able to pull data from the API url in JSON format. I am able to get individual variables from JSON, but I want to display all of the data from the "workers" block into a UITableView. Here is an example of the JSON:
{"username":"n00bminer","balance":"0","total_hashrate":"1429","payout_history":"0.71828344","round_shares":"96908","workers":
{
"n00bminer.1":{"hashrate":"998","last_share_timestamp":"1392906308","accepted_shares":"84755","stale_shares":"913"},
"n00bminer.cpu":
{"hashrate":"0","accepted_shares":"7891","stale_shares":"11"},
"n00bminer.2":{"hashrate":"431","last_share_timestamp":"1392906300","accepted_shares":"13285","stale_shares":"118"}
}}
(bolded is the part that I need) Live data: http://www.ielitepool.com/api.php?api_key=9d9be4bd59eb8de59f1cac981099c43e866b0cc07a5555dd922c9efc08ac31a1
I request this using:
NSData* apiData = [NSData dataWithContentsOfURL:
[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] valueForKey:#"api_url"]]
];
NSDictionary* json = nil;
if (apiData) {
json = [NSJSONSerialization
JSONObjectWithData:apiData
options:kNilOptions
error:nil];
}
and get individual variables using:
float total_hashrate = [[json valueForKey:#"total_hashrate"] floatValue];
How can I get all of the workers, as well as their stats in one UITableView. For example, I don't want the worker name to only display, then have it lead to another UITableViewController, but rather the name and then the stats underneath (hashrate, accepted_shares, etc.)
Following code will print worker's information:
[json[#"workers"] enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSDictionary *obj, BOOL *stop) {
NSLog(#"worker = %# : hashrate = %f last_share_timestamp = %f",
key, [obj[#"hashrate"] floatValue], [obj[#"last_share_timestamp"] floatValue] );
}];
If you will have troubles displaying info in table, please create separate question with code sample.

ios Twitter API JSON parsing

I'm trying to parse the JSON string received by the Twitter API to get the user timeline.
I'm using Jastor to convert the JSON response to objective c objects.
Everything works fine until I try to parse the entities object
entities = {
hashtags =();
media = (
{
"display_url" = "pic.twitter.com/...";
"expanded_url" = "http://...";
id = ...;
"id_str" = ...;
indices =(
5,
25
);
"media_url" = "http://...";
"media_url_https" = "https://...";
sizes ={
large ={
h = 765;
resize = fit;
w = 1024;
};
medium ={
h = 448;
resize = fit;
w = 600;
};
small ={
h = 254;
resize = fit;
w = 340;
};
thumb ={
h = 150;
resize = crop;
w = 150;
};
};
type = photo;
url = "http://...";
}
);
urls =();
"user_mentions" = ();
};
Even if the JSON is not standard Jastor seems to parse all of it but this block due to the presence of "(" ")".
Do you know how to allow Jastor to parse this block as well? Or do I have to change library?
Thank you.
What's curious with the output of your question is that it is not a JSON formatted string. It looks like a nested combination of NSDictionary and NSArray objects which is typical when you convert a JSON string into Objective-C objects. When you NSLog this sort of object, the curly braces indicate NSDictionary objects and the parentheses indicate NSArray objects.
So, it just looks like you're displaying a typical, successfully parsed JSON object. You can decipher it as follows, assuming that the above output was generated by doing a NSLog of some NSDictionary called, say, jsonObject:
NSDictionary *entity = [jsonObject objectForKey:#"entities"];
NSArray *media = [entity objectForKey:#"media"];
NSDictionary *media0 = [media objectAtIndex:0];
NSString *display_url = [media0 objectForKey:#"display_url"];
NSArray *sizes = [media0 objectForKey:#"sizes"];
NSDictionary *size0 = [sizes objectAtIndex:0];
or, if using modern Objective C, simply:
NSDictionary *entity = jsonObject[#"entities"];
NSArray *media = entity[#"media"];
NSDictionary *media0 = media[0];
NSString *display_url = media0[#"display_url"];
NSArray *sizes = media0[#"sizes"];
NSDictionary *size0 = sizes[0];
etc.
Why not using the new feature in iOS 5.0 NSJSONSerialization, it converts JSON data to Objective C standarts like NSArray or NSDictionary.
NSString *stringURL = [NSString stringWithFormat:#"%#?%#", kTwitterApi, kParams];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:stringURL]];
request.HTTPMethod = #"GET";
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"Error%#", error.localizedDescription);
}else {
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&err];
NSLog(#"%#", json);
}
}];

iOS FBRequestConnection startForMyFriendsWithCompletionHandler getting complete list of friends

How can we get the complete list of friends, currently I am using
[FBRequestConnection startForMyFriendsWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// Do stuff
} else {
// Throw error
}
In the response, we get a paging and the next url. Does anyone know how we can loop through the next url's and get the complete list of friends ?
Response has
paging = {
next = "https://graph.facebook.com/1301xxxxxx/friends?fields=id,name,username,first_name,last_name&format=json&access_token=BAAFjJBl9zZBABALFxcbix0aNe0NFOfW8mHCU4ntPaxwooYVo1L6fOWgNTMTZBqLHfxjrWBOXNLjcCwEbkBgZAJX22Ec9PlatgHP9GfjVEWyxk0qGtxxxxxxxxxx&limit=5000&offset=5000&__after_id=10000xxxxxx";
};
Thanks in advance
At first you need to get link on next, you need to extract offset and __after_id parameters,according to iPhone parsing url for GET params you will get dictionary with parameters:
//put here your string with parameters
NSString* next = #"https://graph.facebook.com/1301xxxxxx/friends?fields=id,name,username,first_name,last_name&format=json&access_token=BAAFjJBl9zZBABALFxcbix0aNe0NFOfW8mHCU4ntPaxwooYVo1L6fOWgNTMTZBqLHfxjrWBOXNLjcCwEbkBgZAJX22Ec9PlatgHP9GfjVEWyxk0qGtxxxxxxxxxx&limit=5000&offset=5000&__after_id=10000xxxxxx";
NSArray * pairs = [next componentsSeparatedByString:#"&"];
NSMutableDictionary * kvPairs = [NSMutableDictionary dictionary];
for (NSString * pair in pairs) {
NSArray * bits = [pair componentsSeparatedByString:#"="];
NSString * key = [[bits objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString * value = [[bits objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[kvPairs setObject:value forKey:key];
}
You can get correct parameters by kvPairs[#"__after_id"] and kvPairs[#"offset"]
Next step create add this parameters to your original request, in original request offset and after id should be nil, and you need to filter this situation, if you will do all correct, you will be able to call your ethos recursively

json parsing from the yahoo weather

i am very new to something called JSON Parsing in iOS. Can anybody explain me how to parse data from the scratch. Basically what I am tying to tell is that I am using Yahoo weather api for fetching the weather of a location.http://weather.yahooapis.com/forecastjson?w=2502265 is the link that I am using it .Now how can I parse the data from it?
I am getting error by doing this.Can somebody rectify it or tell me how to do it?
NSString * address = #"http://weather.yahooapis.com/forecastjson?w=2502265";
NSString * request = [NSString stringWithFormat:#"%#",address];
NSURL * URL = [NSURL URLWithString:request];
NSString* JSON = [NSString stringWithContentsOfURL:URL encoding:NSUTF8StringEncoding error:&error];
NSError *e = nil;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:JSON options:NSJSONReadingMutableContainers error:&e];
NSLog(#"%#", json);
I have found that AFNetworking has made my life much easier.
I usually do something more than this like pass in POST parameters, but this will do for your case:
NSURL *url = [NSURL URLWithString:#"http://weather.yahooapis.com/forecastjson?w=2502265"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// PARSE YOUR JSON DICTIONARY HERE
[self parseResult:JSON];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Failed to get data from web service, error: %#", [error localizedDescription]);
}];
[operation start];
// method to parse web service JSON
-(void)parseResult:(id)jsonDictionary
{
// parse result here
NSLog(#"Title = %#", [jsonDictionary valueForKey:#"title"];
}
Hope that helps.
Some basic info for you
What you're doing is requesting information from a web service.
You can think of web service like scripts on the server listening for specific POST or GET parameters.
You might have a web service like this:
http://www.mywebservice.com/rest/datatype=User?name=JohnSmith&age=20
Notice the "datatype", "name" and "age" are the parameters the web service is expecting. When you make a request to the web service, you usually pass in the value (in this case, "User", "JohnSmith" and "20" are the values) to those parameters.
These days, a web service will usually return you the data in the form of JSON or XML.
JSON doesn't have to do all those XML formatting, and as a result, JSON will tend to be more of the preferred choice for returning data.
The JSON data returned will look something like:
{
users = {(
({
name = John Smith;
age = 20;
address = 123 Easy Street EARTH
}),
({
name = Bob Brown;
age = 35;
address = 456 Some Road EARTH
})
)};
}
The above can be a bit intimidating at first but once you deal with it once, you'll realise that these are usually dictionaries nested inside arrays, nested inside giant dictionary.
As in the above case, the returned JSON data is a single giant dictionary containing all users. When you do something like:
[JSON objectForKey:#"users"]
You get the "users" array:
users = {(
({
name = John Smith;
age = 20;
address = 123 Easy Street EARTH
}),
({
name = Bob Brown;
age = 35;
address = 456 Some Road EARTH
})
)};
Then when you want to get a specific user from the "users" array, say Bob Brown, you would do something like:
[[JSON objectForKey:#"users"] objectAtIndex:1]
And that will return you:
{
name = Bob Brown;
age = 35;
address = 456 Some Road EARTH
}
Finally, to get a property of a user such as their name, you can go:
[[[JSON objectForKey:#"users"] objectAtIndex:1] valueForKey:#"name"];
For example:
NSLog(#"User name = %#", [[[JSON objectForKey:#"users"] objectAtIndex:1] valueForKey:#"name"]);
Real web service dictionaries usually aren't that nicely formatted, they're usually a bit more convoluted, especially those CMS like Drupal (run!!!) :D

Resources