How to use Facebook SDK in iOS? - 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".

Related

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.

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

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

Error with uploading photo to facebook by Facebook iOS SDK 3.1.1

I'm developing an app and it allow user to upload their photo to facebook with message.
But it not work smoothly, sometime it works perfect, and it return this error many times.
2012-10-09 21:12:41.320 TimeLapse[1724:707] Error: HTTP status code: 200
2012-10-09 21:12:41.329 TimeLapse[1724:707] Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0xf352290 {com.facebook.sdk:ErrorInnerErrorKey=Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0xf351840 {NSErrorFailingURLStringKey=https://graph.facebook.com/me/photos?sdk=ios&access_token=.....&migration_bundle=fbsdk%3A20121003&message=Ghh&format=json, NSErrorFailingURLKey=https://graph.facebook.com/me/photos?sdk=ios&access_token=....&migration_bundle=fbsdk%3A20121003&message=Ghh&format=json, NSLocalizedDescription=The request timed out., NSUnderlyingError=0xf3518b0 "The request timed out."}, com.facebook.sdk:HTTPStatusCode=200}
Here is my code
-(void)startPostPhotoToFacebook:(UIImage *)image withMessage:(NSString *)message {
NSArray *arrPermission = [NSArray arrayWithObjects:#"publish_stream", nil];
if (FBSession.activeSession.state == FBSessionStateOpen) {
NSLog(#"Session is opened already");
[self postPhotoToFacebook:image withMessage:message];
}
else {
NSLog(#"Need to open session");
[FBSession openActiveSessionWithPublishPermissions:arrPermission defaultAudience:FBSessionDefaultAudienceEveryone allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
if (!error) {
[self sessionStateChangedForPostPhotoToFacebook:session state:state error:error withImage:image andMessage:message];
}
else {
NSLog(#"Open active session failed");
}
}];
}
}
-(void)sessionStateChangedForPostPhotoToFacebook:(FBSession *)session state:(FBSessionState)state error:(NSError *)error withImage:(UIImage *)image andMessage:(NSString *)message {
switch (state) {
case FBSessionStateOpen: {
[self startPostPhotoToFacebook:image withMessage:message];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
default:
break;
}
if (error) {
NSLog(#"error");
}
}
-(void)postPhotoToFacebook:(UIImage *)image withMessage:(NSString *)message {
if (message == nil) {
message = #"";
}
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:message forKey:#"message"];
[params setObject:image forKey:#"source"];
FBRequest *request = [FBRequest requestWithGraphPath:#"me/photos" parameters:params HTTPMethod:#"POST"];
FBRequestConnection *fbConnection = [[FBRequestConnection alloc] initWithTimeout:10];
[fbConnection addRequest:request completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"Result: %#", result);
[myMainViewController finishPostPhotoToFacebook];
[fbConnection release];
}
else {
NSLog(#"%#", error.description);
[myMainViewController errorPostPhotoToFacebook];
[fbConnection release];
}
}];
[fbConnection start];
}
Any one know how to fix this?
Thank you very much
You're seing timeouts from Facebook. See the description
NSLocalizedDescription=The request timed out.,
Your timeout setting is quite short. Facebook SDKs defaults timeout 180.
Since you're dealing with image upload 10 second may not always be enough. Set it higher to something like 30 seconds.

Resources