YouTube Objective-C API video url from playlist item - ios

I am having trouble getting the video url for a YouTube video. I can retrieve the playlist items with a thumbnail and title but I can't get the actual video url.
GTLServiceYouTube *service = [[GTLServiceYouTube alloc] init];
service.APIKey = #"API Key";
GTLQueryYouTube *query = [GTLQueryYouTube queryForPlaylistItemsListWithPart:#"snippet,contentDetails"];
query.playlistId = #"playlist ID";
query.maxResults = 50;
GTLServiceTicket *ticket = [service executeQuery:query
completionHandler:^(GTLServiceTicket *ticket, id object, NSError *error) {
// This callback block is run when the fetch completes
if (error == nil)
{
GTLYouTubeSearchListResponse *products = object;
for (GTLYouTubeSearchResult *item in products)
{
NSLog(#"%#", item.snippet);
NSString *dictionary = [item.snippet JSONValueForKey:#"videoId"];
GTLYouTubeThumbnailDetails *thumbnails = item.snippet.thumbnails;
GTLYouTubeThumbnail *thumbnail = thumbnails.high;
NSString *thumbnailString = thumbnail.url;
if (thumbnailString != nil)
{
[self.thumbnailsArray addObject:thumbnailString];
[self.thumbnailTitleArray addObject:item.snippet.title];
//[self.videos addObject:video];
NSLog(#"id: %#", dictionary);
}
}
}
else
{
NSLog(#"Error: %#", error.description);
}
[self.tableView reloadData];
}];
Does anyone know how to get the video url using the YouTube API?

First of all if you want only videos in your search result you should set type = video.
In your code:
query.playlistId = #"playlist ID";
query.maxResults = 50;
query.type = #"video";
You need to add "id" into part. Your query call will be:
GTLQueryYouTube *query = [GTLQueryYouTube queryForPlaylistItemsListWithPart:#"id,snippet,contentDetails"];
and in response you can get video id with id.videoId. So in your code it will be:
NSString *videoId = item.identifier.videoId;
Once you have the id, you can plug it in:
http://www.youtube.com/watch?v={VIDEO ID HERE}

The video resource in the v3 API does not provide a URL. What you can do instead is to append the video ID to a string. Play page URLs tend to be of the format:
http://www.youtube.com/watch?v={VIDEO ID HERE}

Related

How to Implement and using nextTokenPage using Using GTLRYoutube iOS Objective C

so I have a question how to use & implement nextPageToken Using GTLRYoutube in iOS Objective c which the example result is here :
( https://developers.google.com/youtube/v3/docs/playlistItems/list ) and set the maxResults to "10" and the "nextPageToken will generate it".
btw my flow to get the :
ChannelID
and getting PlaylistID -> to get PlaylistItems
and VideoID one by one
and the code like this :
1.
- (void)fetchChannelResource {
GTLRYouTubeQuery_ChannelsList *query =
[GTLRYouTubeQuery_ChannelsList queryWithPart:#"snippet,contentDetails"];
query.mine = true;
[self.service executeQuery:query
delegate:self
didFinishSelector:#selector(displayResultWithTicket:finishedWithObject:error:)];
}
and execute query :
- (void)displayResultWithTicket:(GTLRServiceTicket *)ticket
finishedWithObject:(GTLRYouTube_ChannelListResponse *)channels
error:(NSError *)error {
if (error == nil) {
NSMutableString *output = [[NSMutableString alloc] init];
if (channels.items.count > 0) {
self.youtubeChannelDataArray = channels.items;
[output appendString:#"Channel information:\n"];
for (GTLRYouTube_Channel *channel in channels) {
NSString *title = channel.snippet.title;
NSString *description = channel.snippet.description;
NSNumber *viewCount = channel.statistics.viewCount;
[output appendFormat:#"Title: %#\nDescription: %#\nViewCount: %#\n", title, description, viewCount];
NSString *uploadID = channel.contentDetails.relatedPlaylists.uploads;
self.youtubeUploadID = uploadID;
}
//CALL fetchPlaylistItemResource
[self fetchPlaylistItemResource];
} else {
[output appendString:#"Channel not found."];
}
// self.output.text = output;
} else {
// [self showAlert:#"Error" message:error.localizedDescription];
}
}
all the data saved in NSArray and NSMutableDictionary.
and in other viewController, i need to display them all.. but the problem is how to implement with nextPageToken which is will display 5 items resultPerPage ??
because when I use this "GTLRYoutube", looks like we don't need to make a new model, just use the model from GTLRYoutube, besides that also didn't make mapping and access the youtube API in the Datamanager.m
anyone have a suggestion or advise ???
thanks before!

Unable to get message array from the Thread List While using gmail Query -queryForUsersThreadsList

We are working on gmail App.
When we are fetching the thread list using query - "queryForUsersThreadsList"
We are unable to get the message list for a thread.
Please find the code bellow
- (void)fetchAllMails {
[self showLoader];
GTLQueryGmail *query = [GTLQueryGmail queryForUsersThreadsList];
NSString * strQuery = [[NSUserDefaults standardUserDefaults]valueForKey:#"priorityQuery"];
query.q = [NSString stringWithFormat:#"%# OR %# ",strQuery,[DataManager sharedManager].contactString];
[self.service executeQuery:query
delegate:self
didFinishSelector:#selector(displayThreadListWithTicket:finishedWithObject:error:)];
}
- (void)displayPriorityMessageListWithTicket:(GTLServiceTicket *)ticket
finishedWithObject:(GTLGmailListThreadsResponse *)emailsResponse error:(NSError *)error
{
if (error == nil)
{
//[self hideLoader];
NSMutableString *labelString = [[NSMutableString alloc] init];
nxtPageToken = emailsResponse.nextPageToken;
[[NSUserDefaults standardUserDefaults]setObject:emailsResponse.nextPageToken forKey:#"priorityNextPageToken"];
NSLog(#"%#",emailsResponse.threads);
for(GTLGmailThread *thread in emailsResponse.threads){
NSLog(#"historyId --- %#",thread.historyId);
NSLog(#"messages ----- %#",thread.messages);
NSArray *arrMessage = thread.messages;
NSLog(#"snippet ---- %#",thread.snippet);
NSLog(#"identifier --- %#",thread.identifier);
}
}
so above we are getting arrMessage = nil;
console
messages -----
here is the responce bellow :-
{
nextPageToken = 06476267169132000279;
resultSizeEstimate = 250;
threads = (
{
historyId = 153697;
id = 1546076d7fd73764;
snippet = "Hi , mobile";
},
{
historyId = 153626;
id = 15460736289d4f7d;
snippet = "";
},
);
}
The Thread dictionary in above json do not contain the key message i.e message array
Any suggestions.
Thanks in advance.

Can't access event name from Facebook graph api response iOS

I am calling the graph api to retrieve my user's events.And I get back an NSDictionary response. My problem is that I'm trying to access the names of the events but can't figure out the correct way of doing it. Can you please help me with this?
My response :
events = {
data = (
{
id = 16245704637388667;
name = "My event name";
place = {
id = 278379712223737;
location = {
city = Beijing;
country = China;
latitude = "53.598408783333";
....
Mycode to retrieve the vent name:
if ([result objectForKey:#"data"]){
NSArray *events = [result objectForKey:#"data"];
NSString *text=#"You don't have events!";
for (NSDictionary* myevent in events) {
NSString *myeventName = [myevent objectForKey:#"name"];
NSLog(#"%#",myeventName);
}
}
Found a solution:
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me/events" parameters: #{#"fields": #"name"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSMutableArray* events = [result objectForKey:#"data"];
events names = [events valueForKey:#"name"];
}
}];`

How do you get the "images" from a twitter feed to show in an iOS app

I have a code that accesses a Twitter feed and puts the text into a table. I then edited the code so I could display the text in my custom fashion in separate views, but I wanted to grab images from the tweets as well, and despite over an hour searching could not find a single reference. I have seen how to "Post" images, but to be clear, I need to get and "display" the images from the tweet in question.
Here are the highlights from my code that handles the Twitter Access:
-(void)twitterTimeLine
{
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if (granted == YES)
{
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
ACAccount *twitterAccount = [arrayOfAccounts lastObject]; // last account on list of accounts
NSURL *requestAPI = [NSURL URLWithString:#"https://api.twitter.com/1.1/statuses/user_timeline.json"];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setObject:#"30" forKey:#"count"];
[parameters setObject:#"1" forKey:#"incude_entities"];
SLRequest *posts = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:requestAPI parameters:parameters];
posts.account = twitterAccount;
[posts performRequestWithHandler:^(NSData *response, NSHTTPURLResponse *urlResponse, NSError *error) {
if (response)
{
// TODO: might want to check urlResponse.statusCode to stop early
NSError *jsonError; // use new instance here, you don't want to overwrite the error you got from the SLRequest
NSArray *array =[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&jsonError];
if (array) {
if ([array isKindOfClass:[NSArray class]]) {
self.array = array;
NSLog(#"resulted array: %#",self.array);
}
else {
// This should never happen
NSLog(#"Not an array! %# - %#", NSStringFromClass([array class]), array);
}
}
else {
// TODO: Handle error in release version, don't just dump out this information
NSLog(#"JSON Error %#", jsonError);
NSString *dataString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"Received data: %#", dataString ? dataString : response); // print string representation if response is a string, or print the raw data object
}
}
else {
// TODO: show error information to user if request failed
NSLog(#"request failed %#", error);
}
self.array = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
if (self.array.count != 0)
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData]; // this part loads into table - important!
});
}
}];
}
}
else
{
NSLog(#"%#", [error localizedDescription]);
}
}];
}
and here is how I display the Tweet
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
NSDictionary *tweet = _array[indexPath.row];
cell.textLabel.text = tweet[#"text"];
//NSString *element = [myArray objectAtIndex:2];
//NSString *element = myArray[2];
// I created some custom views to show the text, but kept the table for testing purposes
TemplateView *tempView = [viewArray objectAtIndex:testCounter];
tempView.TweetView.text = tweet[#"text"];
// -> this was what I was hoping for // tempView.ContentView.image = tweet[#"image"];
testCounter++;
if (testCounter >= 30)
{
testCounter = 0;
}
return cell;
}
I took out the key lines that I think is where I need to look:
tempView.TweetView.text = tweet[#"text"];
tempView.ContentView.image = tweet[#"image"];
// hoping that the latter would work as the first one does, but clearly it's not that simple
This might not be possible, if so, how would I get the images from the "link" (url) and make sure it is an image and not a video or other website?
I could set up a "word search" to grab text starting with http from the tweet and hopefully generate a URL from the string
TwitterKit doesn't seem to support images publicly.. I'm having the same stupid issue. The API internally holds images when using the built in tableview and datasource.. It requires a listID and a Slug.. However, when you want the images via JSON, you are out of luck! Even TWTRTweet object doesn't have entities or media properties!
Not sure how anyone can develop such an awful API.. In any case, I reversed the server calls made internally and found that it sends other "undocumented" parameters..
Example:
TWTRAPIClient *client = [[TWTRAPIClient alloc] init];
NSString *endpoint = #"https://api.twitter.com/1.1/statuses/user_timeline.json";
NSDictionary *params = #{#"screen_name":#"SCREEN_NAME_HERE",
#"count": #"30"};
will return NO MEDIA.. even if you have #"include_entities" : #"true".
Solution:
TWTRAPIClient *client = [[TWTRAPIClient alloc] init];
NSString *endpoint = #"https://api.twitter.com/1.1/statuses/user_timeline.json";
NSDictionary *params = #{#"screen_name":#"SCREEN_NAME_HERE",
#"count": #"30",
#"tweet_mode": #"extended"};
With tweet_mode set to extended (tweet_mode is an undocumented parameter), it will now return the media as part of the response.. This includes the "type" which is "photo" for images.
We can get tweets with images by applying "filter=images" query with "include_entities=true". It'll give tweets with media entities, under which we can see type="photo" and other related data.
For ex:
https://api.twitter.com/1.1/search/tweets.json?q=nature&include_entities=true&filter=images
Try this query at twitter developer console and see the response format: https://dev.twitter.com/rest/tools/console
Hope this will help.

empty json reponse in Foursquare2 venue Explore ios api

I'm working on iOS application with foursquare iOS api , I want to get the recommended near venues. I have used following code & it giving me an empty result .. Where have I done the mistake ? ? ?
NSArray* venues;
//get the foursquare locations
- (void)getTipsForLocation:(CLLocation *)location {
//NSLog(#"lat %f",location.coordinate.latitude);
[Foursquare2 venueExploreRecommendedNearByLatitude:#(location.coordinate.latitude)
longitude:#(location.coordinate.longitude)
near:nil
accuracyLL:nil
altitude:nil
accuracyAlt:nil
query:nil
limit:nil
offset:nil
radius:#(1500)
section:nil
novelty:nil
sortByDistance:1
openNow:0
venuePhotos:0
price:nil
callback:^(BOOL success, id result){
if (success) {
NSDictionary *dic = result;
venues = [dic valueForKeyPath:#"response.venues"];
FSConverter *converter = [[FSConverter alloc]init];
self.nearbyVenues = [converter convertToObjects:venues];
//NSLog(#"venues %#",venues);
//NSLog(#"near by places %#",self.nearbyVenues);
}
else{
NSLog(#" foursquare connecting error");
}
}];
NSLog(#"recommended place array %#",venues);
}
You Can Not pass Nil,In NSNumber & NSString.
NSNumber *emptynumber=[[NSNumber alloc] init];
[Foursquare2 venueExploreRecommendedNearByLatitude:lan longitude:lon near:#"" accuracyLL:emptynumber altitude:emptynumber accuracyAlt:emptynumber query:#"" limit:emptynumber offset:emptynumber radius:#(1500) section:#"" novelty:#"" sortByDistance:YES openNow:YES venuePhotos:YES price:#"" callback:^(BOOL success, id result) {
if (success) {
NSLog(#"secondResult: %#",result);
NSDictionary *dic = result;
NSArray *venues = [dic valueForKeyPath:#"response.venues"];
FSConverter *converter = [[FSConverter alloc] init];
self.venues = [converter convertToObjects:venues];
[self.tableView reloadData];
NSLog(#"Data: %#",venues);
}
}];
It Works For me.

Resources