Facebook Graph API Fetching User's Profile Photo - objective-c

I'm using the Facebook Graph API v2.0. The following call
[FBRequestConnection startWithGraphPath:#"/me/picture" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"%#", result);
} else {
NSLog(#"%#", [error userInfo]);
}
}];
results in this error:
{
NSLocalizedDescription = "Response is a non-text MIME type; endpoints that return images and other binary data should be fetched using NSURLRequest and NSURLConnection";
"com.facebook.sdk:ErrorSessionKey" = "<FBSession: 0x10f036250, state: FBSessionStateOpen, loginHandler: 0x100073a40, appID: 863523550341327, urlSchemeSuffix: , tokenCachingStrategy:<FBSessionTokenCachingStrategy: 0x10f0339c0>, expirationDate: 4001-01-01 00:00:00 +0000, refreshDate: 2014-07-27 17:20:14 +0000, attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(\n installed,\n \"public_profile\",\n email,\n \"user_birthday\",\n \"user_location\",\n \"user_friends\"\n)>";
"com.facebook.sdk:HTTPStatusCode" = 0;
}
Does anyone know why this is happening? All I really need is a response containing a url to my profile picture. In 2012 and earlier, similar questions were asked but the API has changed since then. Please don't mark this as a duplicate unless you're actually sure that the question you redirect me to has a working solution. I've tried a couple of other alternatives such as starting the connection myself and using a graph path such as "/me?fields=picture" but they all result in the same error.

It seems my original call requests an image. To get a text based response that gives a url to the profile photo, the following worked for me:
[FBRequestConnection startWithGraphPath:#"me?fields=picture.height(500),picture.width(500)"completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (error) {
}
}];

For the new Facebook Graph API I use:
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me?fields=id,name,picture" //As many fields as you need
parameters:nil
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if (!error){
NSDictionary *picture = [(NSDictionary*)result objectForKey:#"picture"];
NSDictionary *data = [picture objectForKey:#"data"];
NSString *url = [data objectForKey:#"url"];
NSData *dataImage = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
}
}];
You can more info about user data here

Load profile picture with the help of this URL template
NSString *imgUrl = [NSString stringWithFormat:#"http://graph.facebook.com/%#/picture", user.id];

Related

FBSDKGraphRequest skipped after being logged in through Facebook with Parse

I'm currently having user's log in through Facebook using Parse like so:
// Login PFUser using Facebook
[PFFacebookUtils logInInBackgroundWithReadPermissions:permissionsArray block:^(PFUser *user, NSError *error) {
SHOW_LOADING();
// Eventually kick off a loading animation
if (!error)
{
if (user)
{
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"THE RESULT: %#", result);
}
else
{
NSLog(#"ERROR");
}
}];
}
else
{
}
}
HIDE_LOADING();
}];
I get the log statement saying the user's been logged in, but the FBSDKGraphRequest get's completely skipped and there is no log statement from it at all? I can't seem to get it to get it send the FBSDKGraphRequest no matter what I do. (Tried it with obtaining invitable_friends as well but it got skipped too). By skipping I mean if I set breakpoints, it just hops right over the whole internal code of the FBSDKGraphRequest and no NSLog is displayed.
i think you should call the request after you have login in/sign up the user.TRy again outside logInInBackgroundWithReadPermissions loop.
it should work.
-Also use tagguable_friend instead of invitable_friend

Sharing my ios app details on facebook along with a facebook share

I am adding share functionalities on my facebook app.Like When a "saying" is selected there is a button for sharing that "saying" on facebook.And while clicking this button I can only see the shared saying on my facebook page,there isnt any information about my ios app.How can I make everyone knows that this saying is shared through my iOS app? Please help me....
I may be a little late. Hope this helps.
You have to use the Accounts framework and the Social framework to share with your app name.
First make sure you have set up your App on Facebook correctly. Then you can use the Facebook App ID to share your posts through your app.
Here is a sample code that shows you how to use the Accounts framework with the Social Framework :
ACAccountType * facebookAccountType = [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
// At first, we only ask for the basic read permission
NSArray * permissions = #[#"email"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"275485699289493", ACFacebookAppIdKey, permissions, ACFacebookPermissionsKey, ACFacebookAudienceOnlyMe, ACFacebookAudienceKey, nil];
NSArray *accounts = [self.accountStore accountsWithAccountType:facebookAccountType];
//it will always be the last object with single sign on
self.facebookAccount = [accounts lastObject];
[self.accountStore requestAccessToAccountsWithType:facebookAccountType options:dict completion:^(BOOL granted, NSError *error) {
if (granted && error == nil) {
/**
* The user granted us the basic read permission.
* Now we can ask for more permissions
**/
NSArray *readPermissions = #[ #"publish_actions"];
[dict setObject:readPermissions forKey: ACFacebookPermissionsKey];
[self.accountStore requestAccessToAccountsWithType:facebookAccountType options:dict completion:^(BOOL granted, NSError *error) {
if(granted && error == nil) {
NSDictionary *parameters = #{#"message": #"This Should Work Perfectly !! "};
NSURL *feedURL = [NSURL URLWithString:#"https://graph.facebook.com/me/feed"];
SLRequest *feedRequest = [SLRequest
requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:feedURL
parameters:parameters];
feedRequest.account = self.facebookAccount;
[feedRequest performRequestWithHandler:^(NSData *responseData,
NSHTTPURLResponse *urlResponse, NSError *error)
{
// Handle response
}];
} else {
NSLog(#"error is: %#",[error description]);
}
}];
} else {
NSLog(#"error is: %#",[error description]);
}
}];
}

how to deactivate twitter account in iPhone app that used for Integration

I have app where I am doing the Twitter integration.
I am able to successfully tweets.
Now when I want to de-activate, I am using below.
SLRequest *postRequest1 = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST URL:
[NSURL URLWithString:#"https://api.twitter.com/1/account/end_session.json"]
parameters: [NSDictionary dictionaryWithObject:#"" forKey:#"status"]];
Problem is API with 1 is deprecated and I don't find this method in 1.1.
Is there any alternate for this?
Also what I notice is when I try to activate again, the permission is not asked. It directly send tweet. It ask tweet permission for the first time only. Not after de-activate -- Re-activate process. Is this is how Twitter behaves?
Edit 1
Code I use for all tweet is as below...
if ([self userHasAccessToTwitter]) {
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
// Request access from the user to access their Twitter account
[account requestAccessToAccountsWithType:accountType options:NULL completion:^(BOOL granted, NSError *error)
{
if (granted == YES)
{
///////////////////////////////////////////////
// SEND TEXT ONLY ///
///////////////////////////////////////////////
[[NSUserDefaults standardUserDefaults] setValue:#"yes" forKey:#"twitterLogin"];
[[NSUserDefaults standardUserDefaults] synchronize];
// Populate array with all available Twitter accounts
NSString *message1 = [NSString stringWithFormat:#"Hi! I am using twitter integration."];
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
//use the first account available
ACAccount *acct = [arrayOfAccounts objectAtIndex:0];
SLRequest *postRequest1 = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"http://api.twitter.com/1.1/statuses/update.json"] parameters: [NSDictionary dictionaryWithObject:message1 forKey:#"status"]];
[postRequest1 setAccount:acct];//set account
[postRequest1 performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if(error) {
NSLog(#"error == %#", error);
} else {
NSLog(#"good to go -1- %i", [urlResponse statusCode]);
}
}];
}
}
}];
}
end_session in API v1 never worked as it should anyway. Starting from 1.1 this method was removed and there's no alternative method. The user should decide if he wants to revoke your application access to his twitter account. The only thing you could do is to delete the auth_token.

How to process multiple SLRequest to get friends list in twitter?

I m using the following twitter api to get the friends list:
https://api.twitter.com/1.1/friends/list.json?
And using [SLRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) to get the response data, and perform UI Changes and model data changes in performRequestWithHandler block.
But a single request at the maximum retrieves only 20 friends.(if you set the cursor parameter in api to -1).
I can use the cursor parameter of the api to send request to get the next 20 friends and so on until the cursor value is 0.
cursor parameter can be set to the 'next_cursor' parameter in the response data of the previous request.
But i m not aware of how to call another SLRequest with in the performRequestWithHandler of the previous request, until the 'next_cursor' value in response data of previous request is 0.
Can anybody tell me how to get all the friends using SLRequest or using any other way.
Any help is appreciated.
Thank you.
u can call the next request in the request handler just after you get the response of twitter friends.
Sorry for not elaborating. I thought you would understand.
Here is the code.
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
// Request access from the user to access their Twitter account
[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
{
// Did user allow us access?
if (granted == YES)
{
// Populate array with all available Twitter accounts
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
// Sanity check
if ([arrayOfAccounts count] > 0)
{
[self postRequest];
}
}
}];
- (void)PostRequest
{
// Keep it simple, use the first account available
ACAccount *acct = [arrayOfAccounts objectAtIndex:0];
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:#"Posting video" forKey:#"status"];
// Build a twitter request
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"https://api.twitter.com/1.1/statuses/update.json"] parameters:tempDict];
[postRequest setAccount:acct];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSLog(#"Twitter response, HTTP response: %i", [urlResponse statusCode]);
NSString *output = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", output);
**// calling this again and again will help you with multiple post request.**
[self postRequest]
}];
}
Similar thing can be done for friend list too.
Hope I helped.

How to comment on a post in facebook3.1 using graph api in ios

I use Facebook 3.1 and try comment on a particular post. I have used the following code. I have used the below mentioned permissions also while creating session:
read_stream,offline_access,publish_stream,share_item
The code:
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"This is my comment", #"message", nil];
NSString *string=[NSString stringWithFormat:#"https://graph.facebook.com/153125724720582_184234384932460/comments?access_token=%#",appDelegate.session.accessToken];
[FBRequestConnection startWithGraphPath:string
parameters:params
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
if (error) {
NSLog(#"Error: %#", [error localizedDescription]);
} else {
NSLog(#"Result: %#", result);
}
}];
Response :
Result: {
comments = 1;
id = "https://graph.facebook.com/153125724720582_184234384932460/comments";
}
But my message is not updated on commented post id.
Same code with Post request also I have tried but Response is:
Result: {
"FACEBOOK_NON_JSON_RESULT" = false;
}
You should use an HTTP POST and make sure that the user has granted publish_stream permissions.
You should copy and paste the API call (and the access token) into the Graph Explorer to test your call out.
(Also use the access_token debugger to make sure the permission is there)
You should use this
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"Test Comment", #"message", nil];
[FBRequestConnection startWithGraphPath:#"153125724720582_184234384932460/comments"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (error)
NSLog(#"Error: %#", [error localizedDescription]);
else
NSLog(#"Result: %#", result);
}];