Error while fetching Facebook friends in iOS - ios

I'm trying to fetch facebook friendlist of a logged in user and it works fine in my account, but when I migrated the app details to a new account and changed the app ID and app secret I'm getting this error below
Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0xf89c0b0 {com.facebook.sdk:HTTPStatusCode=400, com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 100;
message = "(#100) Unknown fields: username.";
type = OAuthException;
};
};
code = 400;
}, com.facebook.sdk:ErrorSessionKey=<FBSession: 0xe5a6c30, state: FBSessionStateOpen, loginHandler: 0xe58d5a0, appID: 705259966179163, urlSchemeSuffix: , tokenCachingStrategy:<FBSessionTokenCachingStrategy: 0xf87b180>, expirationDate: 4001-01-01 00:00:00 +0000, refreshDate: 2014-05-20 07:14:50 +0000, attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(
status,
permission
)>}
This is my current code for fetching friends
- (BOOL)retrieveFacebookFriendsForProfileId:(NSString *)fbProfileId completionBlock:(void (^)(NSArray *, NSError *))completionBlock
{
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
if (error) {
NSLog(#"Error");
} else if (session.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler: ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (error) {
//Throws the code 100 error here
completionBlock(nil, error);
}else{
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,NSDictionary* result,NSError *error) {
if(error)
completionBlock(nil, error);
else
{
NSArray *friendJSONs = [result objectForKey:#"data"];
NSMutableArray *friends=[NSMutableArray array];
for(NSDictionary * friendDict in friendJSONs)
{
SocialProfile *friend=[[SocialProfile alloc] initWithDictionary:friendDict socialMedia:kSocialMediaFacebook];
[friends addObject:friend];
}
completionBlock(friends, nil);
}
}];
}
}];
}
}];
return YES;
}
This code works fine if I use my old app Id and secret. I checked the setting in new account and everything is same as I have done in my old account I dont understand what the problem is. Any help is appreciated

According to https://developers.facebook.com/docs/apps/changelog
Friend list now only returns friends who also use your app: The list of friends returned via the /me/friends endpoint is now limited to the list of friends that have authorized your app.
So I changed my above code to this and it gave me list of friends that use the app and not the whole FB friendlist
FBRequest *friendsRequest = [FBRequest requestForGraphPath:#"/me/friends"];

Related

How to use Facebook SDK in iOS?

I am using Facebook sdk in my app and I'm try to login with Facebook button.
This is work in simulator and iPhone 4 but when I'm using iPhone 5 then it's show following error:
error Error Domain=com.facebook.sdk Code=2 "The operation couldn’t be completed. (com.facebook.sdk error 2.)" UserInfo=0x1766e9c0
{com.facebook.sdk:ErrorLoginFailedReason=com.facebook.sdk:SystemLoginCancelled, com.facebook.sdk:ErrorInnerErrorKey=Error Domain=com.apple.accounts Code=7 "The operation couldn’t be completed. (com.apple.accounts error 7.)",
com.facebook.sdk:ErrorSessionKey=<FBSession: 0x1762f0c0, state: FBSessionStateClosedLoginFailed, loginHandler: 0x0, appID: 733184070029762, urlSchemeSuffix: , tokenCachingStrategy:<FBSessionTokenCachingStrategy: 0x17506a20>, expirationDate: (null), refreshDate: (null), attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(null)>}
my code is here:
if ([[FBSession activeSession] isOpen]) {
/*
* if the current session has no publish permission we need to reauthorize
*/
// if ([[[FBSession activeSession] permissions]indexOfObject:#"public_profile"] == NSNotFound)
{
[[FBSession activeSession] requestNewReadPermissions:[NSArray arrayWithObject:#"public_profile"]
completionHandler:^(FBSession *session,NSError *error){
//[self postPhoto];
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"error %#",result);
NSString *facebookId = [result objectForKey:#"id"];
NSLog(#" facebook %#",facebookId );
[self fb_link_check:facebookId];
}
}];
}];
}
}
else
{
FBSession* session = [FBSession activeSession];
[session closeAndClearTokenInformation];
[session close];
[FBSession setActiveSession:nil];
[FBSession openActiveSessionWithReadPermissions:[NSArray arrayWithObject:#"public_profile"] allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (!error && status == FBSessionStateOpen) {
// [self publishStory];
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"error %#",result);
NSString *facebookId = [result objectForKey:#"id"];
NSLog(#" facebook %#",facebookId );
[self fb_link_check:facebookId];
}
}];
}else
{
NSLog(#"error %#",error);
}
}];
}
So, can any one help me on this.
Also, there is another thing that when we download new facebook sdk 3.16.1 and click on it for installation, it give following error:
The operation couldn’t be completed. (com.apple.installer.pagecontroller error -1.)
Couldn't open "facebook-ios-sdk-3.16.1(1).pkg".

Facebook iOS SDK errors – Posting Open Graph Actions

I'm attempting to post an open graph object with an action (using stories) to Facebook, but I always receive an error that doesn't give me any details. I summed up all the code I'm using into a single method for you guys:
- (void)publishToGraph {
NSMutableDictionary<FBOpenGraphObject> *object = [FBGraphObject openGraphObjectForPost];
object.provisionedForPost = YES;
object[#"title"] = #"Example title";
object[#"type"] = #"rs-coupcash";
object[#"description"] = #"Example description";
object[#"url"] = #"http://exampleurl.com/idk";
object[#"image"] = #[#{#"url": #"http://exampleurl.com/example_url.png", #"user_generated" : #"true" }];
[FBSession openActiveSessionWithPublishPermissions:#[#"email", #"public_profile", #"publish_actions"] defaultAudience:FBSessionDefaultAudienceFriends allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
if (!error && state == FBSessionStateOpen) {
[FBRequestConnection startForPostOpenGraphObject:object completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error) {
NSString *objectId = [result objectForKey:#"id"];
NSLog(#"Object ID: %#", objectId);
id<FBOpenGraphAction> actionObject = (id<FBOpenGraphAction>)[FBGraphObject graphObject];
[actionObject setObject:objectId forKey:#"coupon"];
[FBRequestConnection startForPostWithGraphPath:#"/me/rs-coupcash:favorite" graphObject:actionObject completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[[FBSession activeSession] close];
if(!error) {
NSLog(#"OG story posted, story ID: %#", [result objectForKey:#"id"]);
} else {
NSLog(#"Error: %#", error);
}
}];
} else {
NSLog(#"Error: %#", error);
}
}];
} else {
NSLog(#"Error: %#", error);
}
}];
}
The error I get:
Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x114544670 {com.facebook.sdk:HTTPStatusCode=500, com.facebook.sdk:ErrorSessionKey=, expirationDate: 2014-08-26 05:18:45 +0000, refreshDate: 2014-06-27 16:56:32 +0000, attemptedRefreshDate: 0001-12-30 00:00:00 +0000, **permissions**:(
installed,
"public_profile",
email,
"publish_actions"
)>, com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 1;
message = "An unknown error has occurred.";
type = OAuthException;
};
};
code = 500;
}}
I was using the wrong type for the open graph object; I was using just the namespace for the "type" value, it should be "rs-coupcash:coupon" in this case.

Posting picture on Facebook with description using iOS SDK

I am trying to post/share a picture on Facebook.
First, I am getting publish permissions using:
NSArray *permissionsNeeded = #[#"publish_actions"];
[FBRequestConnection startWithGraphPath:#"/me/permissions"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error){
NSDictionary *currentPermissions= [(NSArray *)[result data] objectAtIndex:0];
NSMutableArray *requestPermissions = [[NSMutableArray alloc] initWithArray:#[]];
for (NSString *permission in permissionsNeeded){
if (![currentPermissions objectForKey:permission]){
[requestPermissions addObject:permission];
}
}
if ([requestPermissions count] > 0){
[FBSession.activeSession requestNewPublishPermissions:requestPermissions
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
[self shareDataOnFacebook];
} else {
NSLog(#"%#", error.description);
}
}];
} else {
[self shareDataOnFacebook];
}
} else {
NSLog(#"%#", error.description);
}
}];
If I NSLog the session, I am getting this:
FBSessionStateOpenTokenExtended, loginHandler: 0x15eab870, appID: 719202928131376, urlSchemeSuffix: , tokenCachingStrategy:, expirationDate: 4001-01-01 00:00:00 +0000, refreshDate: 2014-05-10 12:57:41 +0000, attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(
status,
permission,
"publish_actions"
)>
Now, If I try to post the picture using:
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"{image-url}", #"url",
nil
];
/* make the API call */
[FBRequestConnection startWithGraphPath:#"/me/photos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
/* handle the result */
}];
I am getting the error:
Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x15e4f370 {com.facebook.sdk:HTTPStatusCode=403, com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 200;
message = "(#200) Permissions error";
type = OAuthException;
};
};
code = 403;
}, com.facebook.sdk:ErrorSessionKey=, expirationDate: 4001-01-01 00:00:00 +0000, refreshDate: 2014-05-10 12:57:41 +0000, attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(
status,
permission,
"publish_actions"
)>}
Even, If when I get the permissions again, "publish_actions" isn't in the list.
Please guide me what I am doing wrong.
Is there any other way of sharing/posting just picture with description(without any link, which is required for Share dialogue)?
After banging my head for hours, I figured it out.
It seems you need to go into your app Settings on developers.facebook.com, under "Status & Review", and request publish permissions for your app.
If you only need to test it, you can get around by going to Roles and adding the Facebook user you're trying to login with as a developer for your app.
This worked for me.
NSArray *requestPermission = #[#"publish_actions"];
// Open session with public_profile
[FBSession openActiveSessionWithPublishPermissions:requestPermission defaultAudience:FBSessionDefaultAudienceEveryone allowLoginUI:YES
completionHandler:
^(FBSession *session, FBSessionState state, NSError *error) {
if (!error){
// If the session was opened successfully
if (state == FBSessionStateOpen){
// Your code here
NSLog(#"session opened");
[self postToFacebook];
} else {
// There was an error, handle it
NSLog(#" error on opening session = %#",error);
}
}
}];
-(void)postToFacebook{
NSLog(#"post to facebook");
// Put together the dialog parameters
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Sharing Tutorial", #"name",
#"Build great social apps and get more installs.", #"caption",
#"Allow your users to share stories on Facebook from your app using the iOS SDK.", #"description",
#"https://developers.facebook.com/docs/ios/share/", #"link",
#"http://i.imgur.com/g3Qc1HN.png", #"picture",
nil];
// Make the request
[FBRequestConnection startWithGraphPath:#"/me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// Link posted successfully to Facebook
NSLog(#"result: %#", result);
} else {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
NSLog(#"%#", error.description);
}
}];
}

The operation couldn’t be completed. (com.facebook.sdk error 5.) FACEBOOK VIDEO UPLOAD

I wrote following code for uploading video to facebook from iOS device.
-(void)uploadVideo {
NSLog(#"UPload Videio ");
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"mov"];
NSLog(#"Path is %#", filePath);
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#"Video Test Title", #"title",
#"Video Test Description", #"description",
nil];
// [facebook requestWithGraphPath:#"me/videos"
// andParams:params
// andHttpMethod:#"POST"
// andDelegate:self];
if (FBSession.activeSession.isOpen) {
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error) {
NSLog(#"OK: %#", result);
} else
NSLog(#"Error: %#", error.localizedDescription);
}];
} else {
// We don't have an active session in this app, so lets open a new
// facebook session with the appropriate permissions!
// Firstly, construct a permission array.
// you can find more "permissions strings" at http://developers.facebook.com/docs/authentication/permissions/
// In this example, we will just request a publish_stream which is required to publish status or photos.
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_stream",
nil];
//[self controlStatusUsable:NO];
// OPEN Session!
[FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// if login fails for any reason, we alert
if (error) {
// show error to user.
} else if (FB_ISSESSIONOPENWITHSTATE(status)) {
// no error, so we proceed with requesting user details of current facebook session.
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
// [FBRequestConnection setVideoMode:NO];
if(!error) {
NSLog(#"VEEERRRRRRR: %#", result);
} else
NSLog(#"VVEEERRRRREEEERRR: %#", error.localizedDescription);
}];
//[self promptUserWithAccountNameForUploadPhoto];
}
// [self controlStatusUsable:YES];
}];
}
}
This gives me error
The operation couldn’t be completed. (com.facebook.sdk error 5.)
I don't know what is wrong with facebook. It uploads image, text, but in video it gives this error.
NOTE:
It is not due to send again and again, as I also tested by making new account and resetting iOS Device.
sample.mov also exists and works with graph api, but issue is with this SDK.
Thanks.
Few causes for seeing com.facebook.sdk error 5:
Session is is not open. Validate.
Facebook has detected that you're spamming the system. Change video name.
Facebook has a defined limit using the SDK. Try a different app.
Wrong publish permission. Give publish_actions a spin.
more here... ?
Having read this solution. I was able solve this problem.
[FBRequestConnection startWithGraphPath:#"me/videos"
completionHandler:^(FBRequestConnection *connection,
id result, NSError *error)
{
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error)
{
NSLog(#"SUCCESS RESULT: %#", result);
}
else
{
NSLog(#"ERROR: %#", error.localizedDescription);
}
}];
}];
I was having this problem all day when I noticed that my app does not appear in:
Settings App->Facebook->"ALLOW THESE APPS TO USE YOUR ACCOUNT"
This made me realize that posting to Facebook is not permitted by default, you must prompt the user for their permission:
[[FBSession activeSession] requestNewPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error)
{
if (!error)
{
// UPLOAD VIDEO HERE AND THAT ERROR 5 SHOULD GO AWAY
}
}];

Facebook SDK friendlist request

I got a time request timed out error when I try to load all of my facebook friend.
I have FBSessionOpen state.
My code:
[FBRequestConnection startForMyFriendsWithCompletionHandler:^(FBRequestConnection *connection, id data, NSError *error) {
if(error) {
NSLog(#"Error: %#", error);
[self.delegate didFinishLoadingFriendsWithResult:[ErrorResponse errorResponseWithMessage:#"Failed to load user friends from Facebook"] succes:NO];
return;
}
NSArray* friends = (NSArray*)[data data];
NSLog(#"You have %d friends", [friends count]);
NSLog(#"Friends: %#", friends);
[self.delegate didFinishLoadingFriendsWithResult:friends succes:YES];
}];
Error message:
Error: Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x1d1e3a30 {com.facebook.sdk:ErrorInnerErrorKey=Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x1d1e16a0 {NSErrorFailingURLStringKey=https://graph.facebook.com/me/friends?sdk=ios&fields=id%2Cname%2Cusername%2Cfirst_name%2Clast_name&migration_bundle=fbsdk%3A20130120&format=json&access_token=CAAHyDtIdIi0BAM6ZCtXb3Yb5jzuPQ7Tvc6mYg1zO1ZBjoEqZBI5sB5eFYQiTp6s0euVhMTQcl1yqXnaLT118BIBaaEtY1hLEpKq1ptG6y4dHR8BknAOTZCpRUvYlJlT6KbL42MXk2VaMZBvGRwIvs1644FSxy5vVRBSTIFsNZAzIyRpQjjhIA1, NSErrorFailingURLKey=https://graph.facebook.com/me/friends?sdk=ios&fields=id%2Cname%2Cusername%2Cfirst_name%2Clast_name&migration_bundle=fbsdk%3A20130120&format=json&access_token=CAAHyDtIdIi0BAM6ZCtXb3Yb5jzuPQ7Tvc6mYg1zO1ZBjoEqZBI5sB5eFYQiTp6s0euVhMTQcl1yqXnaLT118BIBaaEtY1hLEpKq1ptG6y4dHR8BknAOTZCpRUvYlJlT6KbL42MXk2VaMZBvGRwIvs1644FSxy5vVRBSTIFsNZAzIyRpQjjhIA1, NSLocalizedDescription=The request timed out., NSUnderlyingError=0x1d1e3800 "The request timed out."}, com.facebook.sdk:HTTPStatusCode=200, com.facebook.sdk:ErrorSessionKey=<FBSession: 0x1d1b0c90, state: FBSessionStateOpen, loginHandler: 0x1d1b0db0, appID: 547620445299245, urlSchemeSuffix: , tokenCachingStrategy:<FBSessionTokenCachingStrategy: 0x1d1afdd0>, expirationDate: 2013-09-28 09:49:39 +0000, refreshDate: 2013-07-30 14:08:31 +0000, attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(
"read_friendlists"
)>}
Any idea what I am doing wrong?
Looks like you just did not ask for needed permission from Facebook. Just use
[FBSession openActiveSessionWithReadPermissions:[NSArray arrayWithObjects:#"read_friendlists", #"user_status", #"friends_status", nil] allowLoginUI:allowLoginUI completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
[self sessionStateChanged:session state:status error:error];
}];
And then
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
friendsRequest.session = FBSession.activeSession;
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary* result,
NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
NSLog(#"Found: %i friends", friends.count);
NSLog(#"friends: %#", result);
for (NSDictionary<FBGraphUser>* friend in friends) {
NSLog(#"I have a friend named %# with id %#", friend.name, friend.id);
}
}];
see my answer in StackOverflow for getting facebook friend list with custom design
How to get the list of friend without opening FBFriendPickerViewController iOS

Resources