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!
Related
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.
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.
I am using MapKit to do a local search which returns one or more MKMapItem objects. But there are members of the object I can see in the debugger but I can't access. The one I particularly need is UID.
I have tried item.placemark, but it does not let me access the UID. This seems like it should be really simple. What am I missing here?
This does not work:
NSString *uid = item.placemark.UID
This does not work:
NSDictionary *mapItemDictionary = (NSDictionary *)item;
NSString *uid = [mapItemDictionary objectForKey:#"UID"];
But the debugger command po item shows me all the members of the object:
Name: Shell CurrentLocation: 0 Place: <GEOPlace: 0x17014e650>
{
address = {
business = (
{
**UID = 2478578482074921045**;
URL = "www.shell.com";
canBeCorrectedByBusinessOwner = 1;
name = Shell;
source = (
{
"source_id" = A3H0281540;
"source_name" = "acxiom_us";
},
{
"source_id" = 2276257;
"source_name" = localeze;
}
);
telephone = "+14803968213";
}
);
Any help with this would be appreciated. Here is the code I'm using:
MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];
[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error)
{
[response.mapItems enumerateObjectsUsingBlock:^(MKMapItem *item, NSUInteger idx, BOOL *stop)
{
MKPlacemark *placemark = (MKPlacemark *)item.placemark;
NSDictionary *addressDict = placemark.addressDictionary;
NSArray *businessArray = addressDict[#"business"];// businessArray is NIL
NSString *uid=nil;
if (businessArray != nil && businessArray.count >0) {
NSDictionary *businessDict=businessArray[0];
uid=businessDict[#"UID"];
}
NSLog(#"UID is %#",uid);
}];
Ok, so after a lot of digging it seems that the information is in a couple of private objects. The "place" property is a GEOPlace, and this has a property, business, which is an array that contains a GEOBusiness object. Since this is private data you cannot access it directly via properties, but you can get it via key-value encoding. The following code extracts the UID -
[response.mapItems enumerateObjectsUsingBlock:^(MKMapItem *item, NSUInteger idx, BOOL *stop) {
NSValue *place = [item valueForKey:#"place"];
NSArray *businessArray = (NSArray *)[place valueForKey:#"business"];
NSNumber *uid=nil;
if (businessArray != nil && businessArray.count >0) {
id geobusiness=businessArray[0];
uid=[geobusiness valueForKey:#"uID"];
}
NSLog(#"UID is %#",[uid stringValue]);
}];
As this is private data structures there is no guarantee that it won't change. I am also unsure whether the App store validation process will flag this as private api access - Since it is using valueForKey I don't think it will, but there are no guarantees.
I have an iOS application which downloads and parses a Twitter JSON feed and then presents that feed in a UITableView. This all works fine but I have one question:
When the user taps a UITableView cell, the app will look into the array "tweets_links" and see if that particular tweet has an attached URL, if it does then the web view will appear.
Because not all tweets have website URLs, I have added a simple try catch statement (like in C++) which can tell me if there is an exception when trying to access that part of the array.
My question is: is this is good or bad approach to doing this??
Here is my code:
int storyIndex = indexPath.row;
int url_test = 1;
NSString *url;
#try {
url = [[tweets_links[storyIndex] valueForKey:#"url"] objectAtIndex:0];
}
#catch (NSException *problem) {
// There is NO URL to access for this Tweet. Therefore we get the out of bounds error.
// We will NOT take the user to the web browser page.
// Uncomment the line below if you wish to see the out of bounds exception.
// NSLog(#"%#", problem);
url_test = 0;
}
if (url_test == 1) {
WebBrowser *screen = [[WebBrowser alloc] initWithNibName:nil bundle:nil];
self.seconddata = screen;
seconddata.web_url = url;
screen.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:screen animated:YES completion:nil];
}
else if (url_test == 0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Info" message:#"There is no URL attatched to this Tweet." delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[alertView show];
[tweetTableView deselectRowAtIndexPath:indexPath animated:YES];
}
Is there a much better way of trying to achieve what I am doing???
Thanks, Dan.
Using try and catch is Objective-C isn't encouraged there are other ways checking and handling errors
// firstObject will return the first object in the array or nil if the array is empty.
url = [[tweets_links[storyIndex][#"url"]] firstObject];
if (!url) {
// handle the case for no url
} else {
// do something with url
}
Since sending a message to nil is safe in Objective-C and returns nil it's safe to chain calls. e.g. If the dictionary didn't have an object for that key, then it would return nil and sending firstObject to nil returns nil.
Using either if the below approaches will be fine because TRY CATCH is used to catch programming errors
and use
objectForKey:
instead of
valueForKey:
if ([tweets_links[storyIndex] objectForKey:#"url"] != nil)
OR
if ([url isKindOfClass:[NSString class]])
{
// Code handling the URL
}
else
{
// Code handling there is no URL
}
I don't know a ton about the Twitter feed, but you can probably check for a nil value returned from objectForKey: like so
if ([tweets_links[storyIndex] objectForKey:#"url"] != nil) { /* process the URL */ }
Your code assumes that the value is always an array of at least size = 1, it would be safer to inspect the #"url" key's value before assuming it's an array.
Using exceptions in Objective-C is throwned upon. Exceptions are reserved for programming errors. You don't catch them, you fix the code. With a JSON document, you never have any guarantees what you received, so just be careful.
NSString* url = nil;
NSArray* linksArray = nil;
NSDictionary* linkDict = nil;
NSArray* urlArray = nil;
if ([tweet_links isKindOfClass:[NSArray class]])
linksArray = tweet_links;
if (storyIndex >= 0 && storyIndex < linksArray.count)
linkDict = linksArray [storyIndex];
urlArray = linkDict [#"url"];
if ([urlArray isKindOfClass:[NSArray class]] && urlArray.count > 0)
url = urlArray [0];
if ([url isKindOfClass:[NSString class]])
{
// Code handling the URL
}
else
{
// Code handling there is no URL
}
Note that sending messages to a nil object always returns 0 / NO / nil as appropriate.
And please get into the habit of naming variables properly. You wrote "int url_test = 1;". What does url_test mean? I read the variable name, I have no idea what it means. I need to understand all the code. Making it "int" means it could be 0, 1, 2, 20000 or whatever. If you write instead "BOOL urlValid = YES;" that is clear: It means that you have a valid URL.
Since url value is a NSString value, you could use length to check both if it's nil and if not, if it has any value (not empty string). You can check then if this NSString is a valid url.
- (BOOL) validateUrl: (NSString *) candidate {
NSString *urlRegEx = #"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", urlRegEx];
return [urlTest evaluateWithObject:candidate];
}
....
NSString *url = [[tweets_links[storyIndex][#"url"]] firstObject];
if ([url length] && [self validateUrl: url]) {
// Has a valid URL
}
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}