I am trying to upload a video from my iOS app to Facebook and I am using the code:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"mp4"];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mp4",
#"video/mp4", #"contentType",
#"Video Test Title", #"title",
#"Video Test Description", #"description",
nil];
[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);
}
}];
But I am getting the error:
FBSDKLog: Error for request to endpoint 'me/videos': An open FBSession must be specified for calls to this endpoint.
ERROR: The operation couldn’t be completed. (com.facebook.sdk error 5.)
Can any one please help me?
Log the access token to see if you have a valid one:
NSLog(#"AccessToken:%# ",FBSession.activeSession.accessTokenData.accessToken);
You need to be logged into your app via Facebook and need to have the publish_actions permission granted before you can make a POST request of any sort.
Once you have the access token, to quickly verify if it is valid and has the appropriate permissions, use the access token debugger.
Related
Hi I am trying to post on facebook from my iOS app, before it worked fine. Now I use the latest SDK and following code.
-(void)Authentication{
if (FBSession.activeSession.isOpen) {
[self promptUserWithAccountNameForUploadPhoto];
} else {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_actions",
nil]; // Tried publish_stream too
[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)) {
[self promptUserWithAccountNameForUploadPhoto];
}
}];
}
}
But when it launches Facebook app and login is done, it doen't notify the user about "Post on your behalf", it notifies my app requires your profile details instead.
And when I try to Post like below
-(void)promptUserWithAccountNameForUploadPhoto {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
NSString * msgStr = [NSString stringWithFormat:#"I have added a new Trip to %#",place];
NSString *imgStr = [NSString stringWithFormat:#"%#assets/upload/flags/%#-213x142.png",appDelegate.ServerURL,country];
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",
[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 {
NSLog(#"%#", error.description);
}
}];
}
}];
}
An error comes as -
message = "(#200) The user hasn't authorized the application to perform this action";
from error code it looks like you don't have permission for share
see facebook error codehere
for get sharing permission refer this page
This error is thrown when you are using publish_actions permission without review. For testing purpose you can always make a test user in Roles column of MyApp in developers.facebook.com and then use it..
is it possible, using the Facebook SDK, to get the user info from his user id? An important note is that the user would have approved the application and its permissions before the app make the request.
If it is possible, what is the right way to achieve this? I am trying using this code:
[FBRequestConnection startWithGraphPath:#"/100007046299250"
parameters:nil
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
/* handle the result */
}];
But I get the following error message:
Error for request to endpoint '/100007046299250': An open FBSession must be specified for calls to this endpoint.
Thanks
After login authentication, you can get details from active FBSession like below
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
NSString *firstName = user.first_name;
NSString *lastName = user.last_name;
NSString *facebookId = user.id;
NSString *email = [user objectForKey:#"email"];
NSString *imageUrl = [[NSString alloc] initWithFormat: #"http://graph.facebook.com/%#/picture?type=large", facebookId];
}
}];
}
I want to like a comment of a post on Facebook, I use the same as like the post. For like a post, it works, but for like a comment fail.
Doc:
https://developers.facebook.com/docs/graph-api/reference/object/likes
My Code:
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"/%#/likes", postId_]
parameters:nil
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{ //Error:
}];
The Error is:
Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x158999b0 {com.facebook.sdk:HTTPStatusCode=400, com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 100;
message = "(#100) Error finding the requested story";
type = OAuthException;
};
};
code = 400;
}, com.facebook.sdk:ErrorSessionKey=}
Here is how I do it, and it works like a charm
// post is my module object, encapsulates the info form the post
// pass the post ID
NSString *graphPath = [NSString stringWithFormat:#"%#/likes", post.postID];
FBRequest *request = [FBRequest requestForGraphPath:graphPath];
// DELETE or POST the like
NSString *method = post.liked?#"DELETE":#"POST";
[request setHTTPMethod:method];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
BOOL success = YES;
success = (error)?NO:YES;
if(success) {
}
}];
Note: make sure you have publish permissions
In my project I use the following code:
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:URL, #"object", nil];
if (FBSession.activeSession.isOpen) {
if (FBSession.activeSession.accessTokenData.accessToken) {
[FBRequestConnection startWithGraphPath:#"/me/og.likes"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSLog(#"Just liked on Facebook!");
}];
} else NSLog(#"Cannot open FBSession");
}
There no code for opening or initializing FBSession - I hope, it's not a problem?
I think, we all can trust Facebook, yes? :)
Go to https://developers.facebook.com/docs/reference/opengraph/action-type/og.likes, select "IOS SDK" tab and look at the code.
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?
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
}
}];