facebook.sdk error 5 Objective-C - ios

I'm a newbie in objective-c and I really need your help. I've been trying to solve this for hours now. And I still can't find a solution. Here is my codes:
-(void)post
{
[self connectWithFacebook];
NSLog(#"session: %hhd", FBSession.activeSession.isOpen);
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Here's to the Crazy Ones" ofType:#"mp4"];
NSURL *pathURL = [[NSURL alloc]initFileURLWithPath:filePath isDirectory:NO];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *videoObject = #{
#"title": #"FB SDK 3.1",
#"description": #"hello there !",
[pathURL absoluteString]: videoData
};
FBRequest *uploadRequest = [FBRequest requestWithGraphPath:#"me/videos"
parameters:videoObject
HTTPMethod:#"POST"];
NSLog(#"here i am");
[uploadRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSLog(#"after upload request");
if (!error)
NSLog(#"Done: %#", result);
else
NSLog(#"Error: %#", error.localizedDescription);
}];
}
AND
- (void) connectWithFacebook {
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate openSessionWithAllowLoginUI:YES];
}
And here's from the AppDelegate
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI
{
NSArray *permissions = #[#"publish_stream"];
return [FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
if (error) {
NSLog (#"Handle error %#", error.localizedDescription);
} else {
NSLog(#"No error");
}
}];
}
Here's from the console:
2014-05-08 15:02:49.385 camera[3748:60b] Error: The operation couldn’t be completed. (com.facebook.sdk error 5.)
Your help will be greatly appreciated. Thank you. I really have no idea what to do next.

one possible error for com.facebook.sdk error 5 is
"This status update is identical to the last one you posted. Try
posting something different, or delete your previous update."

Related

FB objective c sharing

I am trying to share a video to facebook but for some reason nothing is shared. I tried it earlier with a image and it worked but when i tried the video it didnt work. Can you not share video to facebook unless its on a web server or something?
Object Code:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"sample_movie" ofType:#"mov"];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary<FBOpenGraphObject> *object = [FBGraphObject openGraphObjectForPost];
object.provisionedForPost = YES;
// for og:title
object[#"title"] = #"Roasted pumpkin seeds";
// for og:type, this corresponds to the Namespace you've set for your app and the object type name
object[#"type"] = #"namespace:video.other";
object[#"video"] = videoData;
Code:
-(void)ShareFB {
[FBRequestConnection startWithGraphPath:#"/me/permissions"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error){
NSDictionary *permissions= [(NSArray *)[result data] objectAtIndex:0];
if (![permissions objectForKey:#"publish_actions"]){
// Permission hasn't been granted, so ask for publish_actions
[FBSession.activeSession requestNewPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound){
// Permission not granted, tell the user we will not share to Facebook
NSLog(#"Permission not granted, we will not share to Facebook.");
} else {
// Permission granted, publish the OG story
[self facebookSharing];
}
} else {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
NSLog(#"Encountered an error requesting permissions: %#", error.description);
}
}];
} else {
// Permissions present, publish the OG story
[self facebookSharing];
}
} else {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
NSLog(#"Encountered an error checking permissions: %#", error.description);
}
}];
}
// When the user is done picking the image
- (void)facebookSharing
{
// Get the image
// UIImage* image = [UIImage imageNamed:#"button"];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"sample_movie" ofType:#"mov"];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary<FBOpenGraphObject> *object = [FBGraphObject openGraphObjectForPost];
object.provisionedForPost = YES;
// for og:title
object[#"title"] = #"Roasted pumpkin seeds";
// for og:type, this corresponds to the Namespace you've set for your app and the object type name
object[#"type"] = #"namespace:video.other";
object[#"video"] = videoData;
// Post custom object
[FBRequestConnection startForPostOpenGraphObject:object completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error) {
// get the object ID for the Open Graph object that is now stored in the Object API
NSString *objectId = [result objectForKey:#"id"];
NSLog(#"object id: %#", objectId);
// create an Open Graph action
id<FBOpenGraphAction> action = (id<FBOpenGraphAction>)[FBGraphObject graphObject];
[action setObject:objectId forKey:#"video.other"];
// create action referencing user owned object
[FBRequestConnection startForPostWithGraphPath:#"/me/namespace:record" graphObject:action completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error) {
NSLog(#"OG story posted, story id: %#", [result objectForKey:#"id"]);
[[[UIAlertView alloc] initWithTitle:#"OG story posted"
message:#"Check your Facebook profile or activity log to see the story."
delegate:self
cancelButtonTitle:#"OK!"
otherButtonTitles:nil] show];
} else {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
NSLog(#"Encountered an error posting to Open Graph: %#", error.description);
}
}];
} else {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
NSLog(#"Encountered an error posting to Open Graph: %#", error.description);
}
}];
}

Facebook iOS SDK: An active access token must be used to query information about the current user

I'm pretty much having the same issue as this post: iOS Facebook SDK: An active access token must be used to query information about the current user, but the solutions don't seem to work for me.
Earlier in the method I call this:
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"user_photos",
#"user_status",
#"read_stream",
nil];
self.fb = [[FBSession alloc] initWithPermissions:permissions];
[self.fb openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error)
{
if(!error){
NSLog(#"Facebook Authorized");
}
if(error){
NSLog(#"Error in fb auth request: %#", error.localizedDescription);
}
}];
And I successfully login with user access. Then, I need to get the users recent posts, so I do this: (FQL)
NSMutableArray *postIDArray = [[NSMutableArray alloc]init];
NSString *query = #"SELECT post_id FROM stream WHERE source_id = me() AND is_hidden = 0 ORDER BY created_time DESC LIMIT 10";
//this was the solution the other SO answer had.
[FBSession setActiveSession:self.fb];
// Set up the query parameter
NSDictionary *queryParam = #{ #"q": query };
// Make the API request that uses FQL
[FBRequestConnection startWithGraphPath:#"/fql"
parameters:queryParam
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
if (error) {
NSLog(#"Error: %#", [error localizedDescription]);
} else if(!error) {
NSLog(#"Result: %#", result);
NSDictionary *resultDict = (NSDictionary *)result;
NSArray *postArr = [resultDict objectForKey:#"data"];
for (FBGraphObject *friendObj in postArr) {
NSString *postIDString = [friendObj objectForKey:#"post_id"];
[postIDArray addObject:postIDString];
}
NSLog(#"postidarray array : %#", postIDArray);
//with post ids, loop through and use graph api to get the post details.
for (int i = 0; i <= postIDArray.count; i++) {
NSString *path = [NSString stringWithFormat:#"https://graph.facebook.com/me/%#",[postIDArray objectAtIndex:i] ];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:path]];
NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSDictionary *postDict = [result yajl_JSON];
NSLog(#"post %d contents: %#",i, postDict);
}
}
}];
}
I can get the post_ID's fine, but then when I try to call
https://graph.facebook.com/me/<my_post_id>
the returned data is:
error = {
code = 2500;
message = "An active access token must be used to query information about the current user.";
type = OAuthException;
};
}
Any idea what's going on? Thanks in advance.
EDIT:
I tried to use
[FBRequestConnection startWithGraphPath:postIDString id result, NSError *error) {
if (error) {
NSLog(#"Error: %#", [error localizedDescription]);
} else if(!error) {
//do some parsing stuff
}
But I get this error:
Error: The operation couldn’t be completed. (com.facebook.sdk error 5.)

How to share video in facebook SDK?

I wrote code as below where file exists in resources. Its not null.
I am successful in adding images, but stuck at videos.
-(void)uploadVideo {
NSLog(#"UPload Videio ");
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"abc" ofType:#"mp4"];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfFile:filePath options:NSDataReadingUncached error:&error];
if(data == nil && error!=nil) {
//Print error description
NSLog(#"error is %#", [error description]);
}
NSLog(#"data is %#", data);
NSDictionary *parameters = [NSDictionary dictionaryWithObject:data forKey:#"sample.mov"];
if (FBSession.activeSession.isOpen) {
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:parameters
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
// [FBRequestConnection setVideoMode:NO];
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:parameters
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
// [FBRequestConnection setVideoMode:NO];
if(!error) {
NSLog(#"Result: %#", result);
} else
NSLog(#"ERROR: %#", error.localizedDescription);
}];
//[self promptUserWithAccountNameForUploadPhoto];
}
// [self controlStatusUsable:YES];
}];
}
}
In return I am getting error as
The operation couldn’t be completed. (com.facebook.sdk error 5.)
How to upload video to facebook using facebook iOS SDK?
Thanks
Here's a method to upload video to Facebook. This code is testing and 100% working.
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
// Specify App ID and permissions
NSDictionary *options = #{ACFacebookAppIdKey: FACEBOOK_ID,
ACFacebookPermissionsKey: #[#"publish_stream", #"video_upload"],
ACFacebookAudienceKey: ACFacebookAudienceFriends}; // basic read permissions
[accountStore requestAccessToAccountsWithType:facebookAccountType options:options completion:^(BOOL granted, NSError *e) {
if (granted) {
NSArray *accountsArray = [accountStore accountsWithAccountType:facebookAccountType];
if ([accountsArray count] > 0) {
ACAccount *facebookAccount = [accountsArray objectAtIndex:0];
NSDictionary *parameters = #{#"description": aMessage};
SLRequest *facebookRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:[NSURL URLWithString:#"https://graph.facebook.com/me/videos"]
parameters:parameters];
[facebookRequest addMultipartData: aVideo
withName:#"source"
type:#"video/mp4"
filename:#"video.mov"];
facebookRequest.account = facebookAccount;
[facebookRequest performRequestWithHandler:^(NSData* responseData, NSHTTPURLResponse* urlResponse, NSError* error) {
if (error == nil) {
NSLog(#"responedata:%#", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
}else{
NSLog(#"%#",error.description);
}
}];
}
} else {
NSLog(#"Access Denied");
NSLog(#"[%#]",[e localizedDescription]);
}
}];
Recommendation:
I think this might be a permissions issue but I am not sure where the error is being thrown. The delegate method that would be thrown is not shown in your code. I think reconciling your code with the steps in this sample might be helpful; if so please accept the answer.
Some key aspects of the sample:
Permissions:
- (IBAction)buttonClicked:(id)sender {
NSArray* permissions = [[NSArray alloc] initWithObjects:
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
[permissions release];
}
Build Request:
- (void)fbDidLogin {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"mov"];
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];
}
Request didLoad delegate method:
- (void)request:(FBRequest *)request didLoad:(id)result {
if ([result isKindOfClass:[NSArray class]]) {
result = [result objectAtIndex:0];
}
NSLog(#"Result of API call: %#", result);
}
Request didFail delegate method:
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(#"Failed with error: %#", [error localizedDescription]);
}
Facebook Video Permissions Link
This Code is Tested successfully On FaceBook SDK 3.14.1
Recommendation: In .plist
set FacebookAppID,FacebookDisplayName,
URL types->Item 0->URL Schemes set to facebookappId prefix with fb
-(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.
Did you ask for a publish_stream permission before?

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.

I got error message : {"error":{"message":"(#200) Permissions error","type":"OAuthException","code":200}} when i do a like action

I want to like a Facebook page, but I got this error:
{"error":{"message":"(#200) Permissions error","type":"OAuthException","code":200}}
As you can see on my code, permissions seems to be OK. Please notice that when I want to like a simple URL like www.google.com, it works!
I got this error only when i want to like a Facebook page.
Here is my code :
-(IBAction) buttonTestRecoFB
{
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_actions",#"publish_stream",
nil];
[FBSession.activeSession closeAndClearTokenInformation];
[FBSession openActiveSessionWithPermissions:permissions allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// session might now be open.
[self sessionStateChanged:session state:status error:error];
}];
}
// FACEBOOK
//
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state)
{
case FBSessionStateOpen:
{
NSLog(#"FBSessionStateOpen");
if (session.isOpen)
{
FBRequest *me = [FBRequest requestForMe];
[me startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *my,
NSError *error) {
NSLog(#"firtname = %#" , my.first_name);
/////////////////////////////////////////////////
NSString *theWholeUrl = [NSString stringWithFormat:#"https://graph.facebook.com/313449204401/likes?access_token=%#", session.accessToken];
NSLog(#"TheWholeUrl: %#", theWholeUrl);
NSURL *facebookUrl = [NSURL URLWithString:theWholeUrl];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:facebookUrl];
[req setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(#"responseData: %#", content);
/////////////////////////////////////////////////
}];
}
}
It's not possible to apply 'like' actions programmatically to Facebook pages. This is stated in the documentation:
For Facebook Pages or websites that do not integrate with Facebook
Authentication, developers should continue to use the Like button
social plugin.

Resources