Facebook iOS SDK errors – Posting Open Graph Actions - ios

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.

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".

Error while fetching Facebook friends in 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"];

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

Create photo album with Facebook SDK on iOS using Open Graph

I need to create a new photo album using the Facebook SDK on iOS. My code was working, but has recently started returning errors like this:
{
"com.facebook.sdk:ErrorSessionKey" = "<FBSession: 0x7290850, state: FBSessionStateOpenTokenExtended, loginHandler: 0x7290c40, appID: 380841565285975, urlSchemeSuffix: , tokenCachingStrategy:<FBSessionTokenCachingStrategy: 0x8a933e0>, expirationDate: 4001-01-01 00:00:00 +0000, refreshDate: 2013-10-14 03:16:01 +0000, attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(\n \"create_note\",\n \"basic_info\",\n \"share_item\",\n \"status_update\",\n \"publish_actions\",\n \"video_upload\",\n email,\n \"photo_upload\",\n installed,\n \"publish_stream\",\n \"user_birthday\",\n \"user_location\"\n)>";
"com.facebook.sdk:HTTPStatusCode" = 500;
"com.facebook.sdk:ParsedJSONResponseKey" = {
body = {
error = {
code = 2;
message = "An unexpected error has occurred. Please retry your request later.";
type = OAuthException;
};
};
code = 500;
};
}
According to https://developers.facebook.com/docs/reference/api/errors/ , and error with code 2 is: "Server-side problem; app should retry after waiting, up to some app-defined threshold".
This has been failing for at least a few days though, and I can't seem to find anyone else having similar trouble, so I'm assuming the problem is my own.
Any ideas what could be the cause? Relevant code is below. The createFacebookAlbum method is the one that is failing.
- (void)shareToFacebook {
if (FBSession.activeSession.isOpen) {
NSLog(#"SESSION IS OPEN");
[self createFacebookAlbum];
} else {
NSLog(#"SESSION IS NOT OPEN");
NSArray* permissions = [NSArray arrayWithObject:#"email"];
[FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
if (error) {
/* handle failure */
NSLog(#"error:%#, %#", error, [error localizedDescription]);
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"There was a problem with your Facebook permissions." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
else if (state == FBSessionStateClosed || state == FBSessionStateClosedLoginFailed ) {
[FBSession.activeSession closeAndClearTokenInformation];
}
else if (state == FBSessionStateOpenTokenExtended || state == FBSessionStateOpen) {
if(!self.presentedFacebookSheet) {
[self performSelector:#selector(reauthorizeAndContinuePostToFacebook) withObject:nil afterDelay:0.5];
self.presentedFacebookSheet = YES;
}
}
}];
}
}
- (void)reauthorizeAndContinuePostToFacebook {
NSArray *permissions = [NSArray arrayWithObjects:#"publish_actions", nil];
[[FBSession activeSession] requestNewPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error) {
[self shareToFacebook];
}];
}
- (void)createFacebookAlbum {
NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
[parameters setObject:#"Test name" forKey:#"name"];
[parameters setObject:#"Test message" forKey:#"message"];
FBRequest* request = [FBRequest requestWithGraphPath:#"me/albums" parameters:parameters HTTPMethod:#"POST"];
NSLog(#"creating facebook album");
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
[connection addRequest:request
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString* albumId = [result objectForKey:#"id"];
NSLog(#"OK %#", albumId);
}
else {
NSLog(#"Error: %#",error.userInfo);
}
}];
[connection start];
}
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error {
switch (state) {
case FBSessionStateOpen:
{
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (error) {
//error
}
else {
NSLog(#"User session found");
}
}];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
}
I had the same problem as you.
One month ago, I could create albums without user_photos.
But now not anymore.
I add the permission: user_photos and it works again.
See also that article on facebook about change to permissions
https://developers.facebook.com/docs/reference/api/album/

Uploading video to Facebook from iOS app using SDK 3.6 intermittently failing

I'm using Facebook SDK 3.6 within an iOS 6.3 app to upload a video to Facebook.
I've looked over many Stack Overflow posts about this but they are all years old and using much older Facebook SDKs.
Sometimes it works, other times it fails with the following message:
unexpected error:Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x1e2affc0 {com.facebook.sdk:HTTPStatusCode=500, com.facebook.sdk:ParsedJSONResponseKey={
body = {
"error_code" = 1;
"error_msg" = "An unknown error occurred";
};
code = 500;
}, com.facebook.sdk:ErrorSessionKey=, expirationDate: 4001-01-01 00:00:00 +0000, refreshDate: 2013-07-30 10:54:22 +0000, attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(
"publish_stream"
)>}
Here is my code:
FBRequestConnection *_currentConnection;
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_stream"]
defaultAudience:FBSessionDefaultAudienceOnlyMe
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
NSError *attributesError;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:url.path error:&attributesError];
NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
long long fileSize = [fileSizeNumber longLongValue];
NSLog(#"file size: %lld", fileSize);
NSString *filename = [url lastPathComponent];
NSLog(#"filename: %#", filename);
NSString *mimeType = [self MIMETypeForFilename:filename
defaultMIMEType:#"video/mp4"];
NSLog(#"mime type: %#", mimeType);
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, filename,
mimeType, #"contentType",
self.song.name, #"title",
_videoDescription, #"description",
nil];
FBRequest *request = [FBRequest requestWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"];
_currentConnection = [request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
self.stageLabel.text = #"";
NSLog(#"result: %#, error: %#", result, error);
if(error) {
// Facebook SDK * error handling *
// if the operation is not user cancelled
if (error.fberrorCategory != FBErrorCategoryUserCancelled) {
[self showAlert:#"Video Post" result:result error:error];
}
self.uploadBarButtonItem.enabled = YES;
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Video Uploaded" message:#"Video has been uploaded"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[self.delegate facebookUploaderUploadSucceeded:self];
}
// Delete the temp video
NSError *err;
[[NSFileManager defaultManager] removeItemAtURL:_sourceURL error:&err];
NSLog(#"Deleting video %#: %#", _sourceURL, [err localizedDescription]);
}];
}];
}
}];
This Code is Tested successfully On FaceBook SDK 3.14.1
-(void)shareOnFaceBook
{
//sample_video.mov is the name of file
NSString *filePathOfVideo = [[NSBundle mainBundle] pathForResource:#"sample_video" ofType:#"mov"];
NSLog(#"Path Of Video is %#", filePathOfVideo);
NSData *videoData = [NSData dataWithContentsOfFile:filePathOfVideo];
//you can use dataWithContentsOfURL if you have a Url of video file
//NSData *videoData = [NSData dataWithContentsOfURL:shareURL];
//NSLog(#"data is :%#",videoData);
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#"Video name ", #"name",
#"description of Video", #"description",
nil];
if (FBSession.activeSession.isOpen)
{
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error)
{
NSLog(#"RESULT: %#", result);
[self throwAlertWithTitle:#"Success" message:#"Video uploaded"];
}
else
{
NSLog(#"ERROR: %#", error.localizedDescription);
[self throwAlertWithTitle:#"Denied" message:#"Try Again"];
}
}];
}
else
{
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_actions",
nil];
// OPEN Session!
[FBSession openActiveSessionWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceEveryone allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if (error)
{
NSLog(#"Login fail :%#",error);
}
else if (FB_ISSESSIONOPENWITHSTATE(status))
{
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error)
{
[self throwAlertWithTitle:#"Success" message:#"Video uploaded"];
NSLog(#"RESULT: %#", result);
}
else
{
[self throwAlertWithTitle:#"Denied" message:#"Try Again"];
NSLog(#"ERROR: %#", error.localizedDescription);
}
}];
}
}];
}
}
And I GOT Error:
The operation couldn’t be completed. (com.facebook.sdk error 5.)
It happens when facebook is being inited. Next time i open my app, it works fine, its always the first time. Tried everything in app, but it seems to be on the Facebook SDK side.
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.

Resources