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"];
}
}];`
Related
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.
I'm tearing my hair out. I'm using the Facebook SDK in an iOS application to request the score of a player. The response I get looks like this when output to the console:
{
data = (
{
application = {
id = 790595290993938;
name = "Laser Blast";
};
score = 100;
user = {
id = 10152606174287397;
name = "Chris Koncewicz";
};
}
);
}
How do I get the value for the score? I've tried making an NSDictionary using:
NSDictionary *d = [NSJSONSerialization JSONObjectWithData:result options:kNilOptions error:&error];
However, I can't see how to access the score value.
Any help greatly appreciated.
EDIT:
This is the code snippet that runs the request and where I'm trying to work with the response:
[getScore startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
NSLog(#"%#", result);
NSDictionary *d = [NSJSONSerialization JSONObjectWithData:result options:kNilOptions error:&error];
}];
You might overlooked the fact numbers are stored as NSNumber objects in collections:
NSInteger score = facebookJson[#"data"][0][#"score"].integerValue;
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 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}