Get and show images from Facebook in iOS app - objective-c

I'm developing a iOS app for iPad. I've implemented Instagram API so I can get and use the photos from the user. Can I do the same but with Facebook? Is there any way to access to users' pictures?
Thanks

The Graph API is where you want to start to see what data you're looking for. For user photos, check out:
Albums user has created -
https://developers.facebook.com/docs/reference/api/user/
Info about a photo -
https://developers.facebook.com/docs/reference/api/photo/
I recommend trying different queries using the Graph API explorer:
https://developers.facebook.com/tools/explorer
First make sure you ask for user_photos permission
Entering me/albums in the query gives you a list of albums for the logged in user. Click on an album's ID in the results to see the info for that album. Enter /photos to see photos for that album.
Once you know what you want you can take a look at the iOS SDKs that are built on top of the Graph API and other APIs to authenticate and for what you're interested in, to grab photos.
For iOS SDK info on making requests, see:
https://developers.facebook.com/docs/reference/ios/3.1/class/FBRequestConnection#startWithGraphPath%3AcompletionHandler%3A
So if you want to see say the photos for one album, given an album_id, you would use request code like:
[FBRequestConnection startWithGraphPath:#"<album_id>/photos"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog("Results: %#", result);
}
}
];
Make sure you've asked for user_photos permissions first.

- (IBAction)btnFBTap:(id)sender {
[FBSDKProfile enableUpdatesOnAccessTokenChange:YES];
if ([FBSDKAccessToken currentAccessToken]) {
[self FBLogin];
} else {
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login
logInWithReadPermissions: #[#"public_profile", #"user_photos"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
// Process error
} else if (result.isCancelled) {
// Handle cancellations
} else {
[self FBLogin];
// If you ask for multiple permissions at once, you
// should check if specific permissions missing
}
}];
}
}
- (void)FBLogin {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me"
parameters:#{#"fields":#"id"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
[[MDManager sharedInstance].loadingView hide];
if (!error) {
NSLog(#"fetched user:%#", result);
// For more complex open graph stories, use `FBSDKShareAPI`
// with `FBSDKShareOpenGraphContent`
/* make the API call */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:[NSString stringWithFormat:#"/%#/photos", result[#"id"]]
parameters:#{#"type":#"uploaded",
#"fields":#"link,height,width"}
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
NSLog(#"%#",result); // Return uploaded photos
}];
}
}];
}

Related

Parse and Facebook sdk 4.1 login and signup returning "User Cancelled Login" Objective-C

I recently updated my Parse SDK to 1.7.4 and Facebook SDK to 4.1, but for getting user data a code that was working in Facebook SDK 3.22.2 is not working in Facebook SDK 4.1. I'm getting error:
Unknown type name 'FBRequest'; did you mean 'SKRequest'?
- (void)requestFacebook:(PFUser *)user
{
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (error == nil)
{
NSDictionary *userData = (NSDictionary *)result;
[self processFacebook:user UserData:userData];
}
else
{
[PFUser logOut];
[ProgressHUD showError:#"Failed to fetch Facebook user data."];
}
}];
}
Thanks for help after verificationwith de link, my i changed my code into this one and worked fine but in iOS 8.1 it's no etch Facebook user data
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me"
parameters:nil];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (error == nil)
{
NSDictionary *userData = (NSDictionary *)result;
[self processFacebook:user UserData:userData];
}
else
{
[PFUser logOut];
[ProgressHUD showError:#"Failed to fetch Facebook user data."];
}
}];
The new Facebook SDK 4.x is now divided into 3 main parts: FBSDKCoreKit, FBSDKLoginKit and FBSDKShareKit.
The new SDK has replaced FBRequest with FBSDKGraphRequest and FBSDKGraphRequestConnection which are in FBSDKCoreKit. Import this into your code and modify your implementation accordingly. You can see an example of how to use the new classes here.

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]);
}
}];
}

Retrieve facebook friends & invite them to my iOS app

I am developing an iOS application in which I want to retrieve my facebook friends & send it to server for checking who are already using this app using their email or phone number. Once I get friends who are not using my application then I will show "Invite" button to send an email to their email address with app store link to download the app.
But as per facebook permissions , we can not retrieve the facebook friends email address.
Can anybody know how can I implement this feature in other way ?
Any kind of help is appreciated. Thanks.
you can not retrieve facebook friends email address but you can post on their wall whatever link you want to post i.e. app store link to download the app.
You can give a look to my this thread.
Since facebook does not provide email address so the idea behind this solution to offer is that, you can send invite friend request with the link to your application at AppStore. I have briefly described the steps in link to follow in order to accomplish this case.
Invitation message might look like this:
I would like you to try XYZ game. Here is the link for this
Application at AppStore:
Facebook iOS SDK - get friends list
You can use FB Graph API(/me/invitable_friends) as below for getting non app friends -
// m_invitableFriends - global array which will hold the list of invitable friends
- (void) getAllInvitableFriends
{
NSMutableArray *tempFriendsList = [[NSMutableArray alloc] init];
NSDictionary *limitParam = [NSDictionary dictionaryWithObjectsAndKeys:#"100", #"limit", nil];
[self getAllInvitableFriendsFromFB:limitParam addInList:tempFriendsList];
}
- (void) getAllInvitableFriendsFromFB:(NSDictionary*)parameters
addInList:(NSMutableArray *)tempFriendsList
{
[FBRequestConnection startWithGraphPath:#"/me/invitable_friends"
parameters:parameters
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
NSLog(#"error=%#",error);
NSLog(#"result=%#",result);
NSArray *friendArray = [result objectForKey:#"data"];
[tempFriendsList addObjectsFromArray:friendArray];
NSDictionary *paging = [result objectForKey:#"paging"];
NSString *next = nil;
next = [paging objectForKey:#"next"];
if(next != nil)
{
NSDictionary *cursor = [paging objectForKey:#"cursors"];
NSString *after = [cursor objectForKey:#"after"];
//NSString *before = [cursor objectForKey:#"before"];
NSDictionary *limitParam = [NSDictionary dictionaryWithObjectsAndKeys:
#"100", #"limit", after, #"after"
, nil
];
[self getAllInvitableFriendsFromFB:limitParam addInList:tempFriendsList];
}
else
{
[self replaceGlobalListWithRecentData:tempFriendsList];
}
}];
}
- (void) replaceGlobalListWithRecentData:(NSMutableArray *)tempFriendsList
{
// replace global from received list
[m_invitableFriends removeAllObjects];
[m_invitableFriends addObjectsFromArray:tempFriendsList];
//NSLog(#"friendsList = %d", [m_invitableFriends count]);
[tempFriendsList release];
}
For Inviting non app friend -
you will get invite tokens with the list of friends returned by me/invitable_friends graph api. You can use these invite tokens with FBWebDialogs to send invite to friends as below
- (void) openFacebookFeedDialogForFriend:(NSString *)userInviteTokens {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
userInviteTokens, #"to",
nil, #"object_id",
#"send", #"action_type",
actionLinksStr, #"actions",
nil];
[FBWebDialogs
presentRequestsDialogModallyWithSession:nil
message:#"Hi friend, I am playing game. Come and play this awesome game with me."
title:nil
parameters:params
handler:^(
FBWebDialogResult result,
NSURL *url,
NSError *error)
{
if (error) {
// Error launching the dialog or sending the request.
NSLog(#"Error sending request : %#", error.description);
}
else
{
if (result == FBWebDialogResultDialogNotCompleted)
{
// User clicked the "x" icon
NSLog(#"User canceled request.");
NSLog(#"Friend post dialog not complete, error: %#", error.description);
}
else
{
NSDictionary *resultParams = [g_mainApp->m_appDelegate parseURLParams:[url query]];
if (![resultParams valueForKey:#"request"])
{
// User clicked the Cancel button
NSLog(#"User canceled request.");
}
else
{
NSString *requestID = [resultParams valueForKey:#"request"];
// here you will get the fb id of the friend you invited,
// you can use this id to reward the sender when receiver accepts the request
NSLog(#"Feed post ID: %#", requestID);
NSLog(#"Friend post dialog complete: %#", url);
}
}
}
}];
}

Why can't I access the facebook friends list after reopening a session in ios

I am upgrading to the facebook 3.0 sdk for ios. Things went well, until I tried to open an existing session after relaunching the application. I am trying to access the list of friends for the facebook user.
if ([[FBSession activeSession] isOpen]) {
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
//do something here
}];
}else{
[[self session] openWithCompletionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if ([self isValid]) {
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
//log this error we always get
NSLog(#"%#",error);
//do something else
}];
}
}];
}
However I get this error:
Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x1d92ff40 {com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 2500;
message = "An active access token must be used to query information about the current user.";
type = OAuthException;
};
};
code = 400;
}, com.facebook.sdk:HTTPStatusCode=400}
I've found that if I use the FBSession reauthorize method it allows me to complete the request without error, but it also means I must show UI or switch apps every time we relaunch the application which is unacceptable. Any suggestions on what I should be doing differently?
I was not setting the session on the request after logging in. Simple mistake.
[[self session] openWithCompletionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if ([self isValid]) {
//I should have been doing this
request.session = [FBSession activeSession];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
//log this error we always get
NSLog(#"%#",error);
//do something else
}];
}
}];