how can I access friends' facebook profile picture? - ios

I need to access friends' profile pictures to display them in my game leaderboard. Most of the links to posts I found here on stackoverflow do not exist anymore. How can I access the profile pictures in a way similar to how I accessed the scores and names in the code below.
-(void)getLeaderboardInfo
{
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%llu/scores?fields=score,user", kuFBAppID] parameters:nil HTTPMethod:#"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (result && !error)
{
int index = 0;
for (NSDictionary *dict in [result objectForKey:#"data"])
{
NSString *name = [[[[dict objectForKey:#"user"] objectForKey:#"name"] componentsSeparatedByString:#" "] objectAtIndex:0];
NSString *strScore = [dict objectForKey:#"score"];
// how do I get the objectforkey representing the image?
m_pLeaderboardEntries[index].pFriendName.text = [NSString stringWithFormat:#"%d. %#", index+1, name];
m_pLeaderboardEntries[index].pFriendScore.text = [NSString stringWithFormat:#"Score: %#", strScore];
// how do I add the image to my leaderboard entries?
index++;
if (index>5) {
break;
}
}
}
}];
}
The LeaderboardInstance
struct LeaderboardboardInstance
{
__unsafe_unretained UILabel *pFriendName;
__unsafe_unretained UILabel *pFriendScore;
__unsafe_unretained UIImage *profilePicture;
};
Also,
struct LeaderboardboardInstance m_pLeaderboardEntries[m_kuLeaderboardSize];

Add this to your list of fields
picture.type(large)
In the result object you should then have a dictionary called picture which contains image info including the url of the users image

Assuming you have a Facebook user logged in and the friend's Facebook ID, this is the way to go:
NSString *imageUrl = [NSString stringWithFormat:#"http://graph.facebook.com/%#/picture?type=large", friendID];
Then you can download the image using NSURLConection or whatever library you want.

Related

How to get Mobile Number from vCard String Objective C

I am working on Action Extension Objective C. I have successfully created Extension for share recent contact in my Extension. In that I am getting v Card String. How can I get Mobile Number from v Card String. Any help would be appreciated.
Using contactsWithData:error: class method of CNContactVCardSerialization, you can retrieve info from a vCard.
It's from Contacts.framework, available since iOS9.
For earlier version, you can use AddressBook.framework. You can read info here.
NSError *errorVCF;
NSArray *allContacts = [CNContactVCardSerialization contactsWithData:[contactStr dataUsingEncoding:NSUTF8StringEncoding] error:&errorVCF];
if (!errorVCF)
{
NSMutableString *results = [[NSMutableString alloc] init];
//NSLog(#"AllContacts: %#", allContacts);
for (CNContact *aContact in allContacts)
{
NSArray *phonesNumbers = [aContact phoneNumbers];
for (CNLabeledValue *aValue in phonesNumbers)
{
CNPhoneNumber *phoneNumber = [aValue value];
[results appendFormat:#"%# %#\n", [aValue label], [phoneNumber stringValue]];
}
}
NSLog(#"Final: %#", results);
}

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.

How to get user interests from the native iOS Facebook SDK?

I've been reading through the documentation, and I couldn't find anything. For other properties like name, id, etc, they're available in the FBGraphUser class. What I need though is the interest list for the user. I believe I have to use the FBGraphObject class, but I'm not really sure how to go about doing so. Any guidance would be very appreciated. Thanks!
me/interests is how you get the interests of the user. if you're looking for someone else, like the user's friend, then id/interests
This counts on the user being signed in
-(void)fbRequest{
[FBRequestConnection startWithGraphPath:#"me/interests" completionHandler:^(FBRequestConnection *connection,NSDictionary<FBGraphObject> *result,NSError *error){
if(!error){
NSArray *data = [result objectForKey:#"data"];
[self updateInterests:data];
}else{
}
}];
}
-(void)updateInterests:(NSArray*)interests
{
NSString *str = self.groupList.text;
for(FBGraphObject <FBGraphUser>*interest in interests) //Using FBGraphUser because it implements name though I'd love to use something else
{
str = [str stringByAppendingFormat:#"%#\n",interest.name ];
}
[self.groupList setText:str];
}
an alternative to the above method does not rely on the coincidence that graphuser has name, so here it is
-(void)updateInterests:(NSArray*)interests
{
NSString *str = self.groupList.text;
for(FBGraphObject *interest in interests) //Using FBGraphUser because it implements name though I'd love to use something else
{
str = [str stringByAppendingFormat:#"%#\n",[interest objectForKey:#"name"] ];
}
[self.groupList setText:str];
}

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

Resources