I am making a test app through that I want to post video on facebook. I am using latest sdk of facebook. But I am not able to post it on facebook.
My code is as below.
NSDictionary *parameters = [NSDictionary dictionaryWithObject:videoData forKey:#"CareAppDemo.mov"];
FBRequest *request = [FBRequest requestWithGraphPath:#"me/videos" parameters:parameters HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSLog(#"result: %#, error: %#", result, error);
}];
Please help me to post video on facebook via my app.
You need to download FacebookSDK first
and then add following framework into your project
FacebookSDK.framework, FBSDKLoginKit.framework, FBSDKShareKit.framework,
Bolts.framework,FBSDKCoreKit.framework
import them,
and write followin code
if(![FBSDKAccessToken currentAccessToken])
{
FBSDKLoginManager *login1 = [[FBSDKLoginManager alloc]init];
[login1 logInWithPublishPermissions:#[#"publish_actions"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
video.videoURL = videoAssetURL;
FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
content.video = video;
[FBSDKShareDialog showFromViewController:self withContent:content delegate:nil];
}];
}
else {
FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
video.videoURL = videoAssetURL;
FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
content.video = video;
[FBSDKShareDialog showFromViewController:self withContent:content delegate:nil];
}
The video URL videoURL must be an asset URL. You can get a video asset URL e.g. from UIImagePickerController.
or for recording video you can take as follow
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:[NSURL URLWithString:[[NSHomeDirectory() stringByAppendingPathComponent:#"Library/Caches"] stringByAppendingFormat:#"/current.mov"]] completionBlock:^(NSURL *assetURL, NSError *error)
{
videoAssetURL =assetURL;
}];
for more detail you can use https://developers.facebook.com/docs/sharing/ios
Successfully tested On FaceBook SDK 3.14.1
Recommendation: 3 properties in .plist file
set FacebookAppID,FacebookDisplayName,
URL types->Item 0->URL Schemes set to facebookappId prefix with fb See
-(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);
}
}];
}
}];
}
}
I GOT Error In first time of App runs:
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.
many more....
Get the publish permission
NSArray* permissions = [[NSArray alloc] initWithObjects:
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
[permissions release];
Try this
- (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];
}
Best Example to upload video on Facebook Check it
Download from below link that's only iPhone
This is the old thread but for all the future readers coming, here is how to do it with the currently latest facebook SDK (v3.24.0 - September 10th 2015).
- (IBAction)bntShareOnFacebookAction:(id)sender {
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]) {
[self shareVideoOnFacebook];
} else {
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logOut]; //very important line for login to work
[loginManager logInWithPublishPermissions:#[#"publish_actions"]
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if(!error) {
[self shareVideoOnFacebook];
}
}];
}
}
- (void) shareVideoOnFacebook {
NSString *videoPath = #"/Documents/.../movie.mov";
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:videoPath]];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:3L];
[params setObject:videoData forKey:#"video_filename.MOV"];
[params setObject:#"Title for this post." forKey:#"title"];
[params setObject:#"Description for this post." forKey:#"description"];
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"/me/videos" parameters:params HTTPMethod:#"POST"]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
//video posted
}
}];
}
IF you want to Upload/Video sharing you must need to pass the Assets Library URL for the original version of the picked item.
URL e.g assets-library://asset/asset.MOV?id=18BC70A0-208A-4F03-A207-7D57C8863425&ext=MOV
If you are using
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
Then you must need to pass
NSURL *url = [info objectForKey:UIImagePickerControllerReferenceURL];
If you using Document Directory Path then first you need to save video into library. You must need to create url link Assets Library URL.
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:videoURL];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (success) {
// Fetch Last saved video.
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:false]];
// Get video url.
PHAsset *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeVideo options:fetchOptions].firstObject;
NSString *assetID = [fetchResult.localIdentifier substringToIndex:(fetchResult.localIdentifier.length - 7)];
NSURL *assetURL = [NSURL URLWithString:[NSString stringWithFormat:#"assets-library://asset/asset.MOV?id=%#&ext=MOV", assetID]];
// Share Video.
FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
video.videoURL = assetURL;
FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
content.video = video;
FBSDKShareDialog *shareDialog = [[FBSDKShareDialog alloc] init];
shareDialog.shareContent = content;
shareDialog.delegate = (id)self;
shareDialog.fromViewController = self;
NSError * error = nil;
BOOL validation = [shareDialog validateWithError:&error];
if (validation) {
dispatch_async(dispatch_get_main_queue(), ^{
[shareDialog show];
});
} else {
NSLog(#"%#", error.localizedDescription);
}
}
}];
Related
I have used the Facebook API to publish videos on Facebook and I'm now working on iOS to do the same. The APIs look very similar however they are missing the contentTitle and description. How do I set that? My API usage below works perfect just missing those two fields. Anyone know how to include that?
NSURL *videoURL = [NSURL fileURLWithPath:videoPath];
FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
video.videoURL = videoURL;
FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
content.video = video;
// Upload video
[FBSDKShareAPI shareWithContent:content delegate:self];
try this code because in this method you can share only video not text and description
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"contact_email"]) {
NSData *videoData = [NSData dataWithContentsOfURL:appDelegateObj.finalVideoUrl];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:3L];
[params setObject:videoData forKey:#"videofilename.MOV"];
[params setObject:#"Your post title" forKey:#"title"];
[params setObject:#"Your post description" forKey:#"description"];
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"/me/videos" parameters:params HTTPMethod:#"POST"]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
//video posted
NSLog(#"successfull %#:",result);
strFbSocialPostId = [result valueForKey:#"id"];//post ID
}
}];
}
UIImage *image = [UIImage imageNamed:#"attachment_blank.png"];
FBSDKSharePhoto *photo = [FBSDKSharePhoto photoWithImage:image userGenerated:NO];
NSDictionary *properties = #{
#"og:type": #"app:recipe",
#"og:title": #"Sample Recipe",
#"og:description": #"",
#"og:url": #"http://samples.ogp.me/216213502062059",
#"og:image": #[photo]
};
FBSDKShareOpenGraphObject *object = [FBSDKShareOpenGraphObject objectWithProperties:properties];
FBSDKShareAPI *shareAPI = [[FBSDKShareAPI alloc] init];
[shareAPI createOpenGraphObject:object];
The submission guidelines speak about a "user generated photos" permission that doesn't seem to be available anywhere in the app settings, or anywhere else in the documentation. Is that still required? Is there a similar permission for images?
You can try this method to share an image with link. The image you want to share should need to be on server(i.e. you need to use link of an image )
Note:- You must have an "publish_actions" permission from facebook app
Below method is shown using the facebook sdk 4.3
In .h file
#import <FacebookSDK/FacebookSDK.h>
#property (strong, nonatomic) FBRequestConnection *requestConnection;
In .m file
-(IBAction)facebookBtn:(id)sender{
if (!FBSession.activeSession.isOpen) {
// if the session is closed, then we open it here, and establish a handler for state changes
[FBSession openActiveSessionWithReadPermissions:#[#"public_profile", #"email", #"user_events", #"user_location", #"publish_actions"]
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
if (error)
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(#"Error", nil) message:error.localizedDescription delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
if (error.code!=2)
{
[alertView show];
}
}
else if (session.isOpen)
{
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self requestCompleted:connection forFbID:#"me" result:result error:error];
}];
// create the connection object
FBRequestConnection *newConnection = [[FBRequestConnection alloc] init];
// create a handler block to handle the results of the request for fbid's profile
FBRequestHandler handler =
^(FBRequestConnection *connection, id result, NSError *error) {
// output the results of the request
[self requestCompleted:connection forFbID:#"me" result:result error:error];
[self showAlert:NSLocalizedString(#"Posted successfully", nil)];
};
// create the request object, using the fbid as the graph path
// as an alternative the request* static methods of the FBRequest class could
// be used to fetch common requests, such as /me and /me/friends
NSString *messageString=[NSString stringWithFormat:NSLocalizedString(#"Just parked at %# with #ParkHero", nil),#"miami"];
NSString *imageUrl = #"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRFoE4FjiykSb-3usYJ6OuyUsa_NB0s0B13u52IKK80se0qOwPJ" ;
// Your facebook application link
NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"https://www.facebook.com/ParkHero?fref=ts", #"link",imageUrl, #"picture",messageString,#"message",nil];
FBRequest *request=[[FBRequest alloc] initWithSession:FBSession.activeSession graphPath:#"me/feed" parameters:params HTTPMethod:#"POST"];
[newConnection addRequest:request completionHandler:handler];
// if there's an outstanding connection, just cancel
[self.requestConnection cancel];
// keep track of our connection, and start it
self.requestConnection = newConnection;
[newConnection start];
}
}];
}
else
{
FBRequestConnection *newConnection = [[FBRequestConnection alloc] init];
// create a handler block to handle the results of the request for fbid's profile
FBRequestHandler handler = ^(FBRequestConnection *connection, id result, NSError *error) {
// output the results of the request
[self requestCompleted:connection forFbID:#"me" result:result error:error];
[self showAlert:NSLocalizedString(#"Posted successfully", nil)];
};
// create the request object, using the fbid as the graph path
// as an alternative the request* static methods of the FBRequest class could
// be used to fetch common requests, such as /me and /me/friends
NSString *messageString=[NSString stringWithFormat:NSLocalizedString(#"Just parked at %# with #ParkHero", nil),#"miami"];
NSString *imageUrl = #"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRFoE4FjiykSb-3usYJ6OuyUsa_NB0s0B13u52IKK80se0qOwPJ";
// Your facebook application link
NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"https://www.facebook.com/ParkHero?fref=ts", #"link",imageUrl, #"picture",messageString,#"message",nil];
FBRequest *request=[[FBRequest alloc] initWithSession:FBSession.activeSession graphPath:#"me/feed" parameters:params HTTPMethod:#"POST"];
[newConnection addRequest:request completionHandler:handler];
// if there's an outstanding connection, just cancel
[self.requestConnection cancel];
// keep track of our connection, and start it
self.requestConnection = newConnection;
[newConnection start];
}
}
I am making a test app through that I want to post a video on facebook. I am using latest sdk of facebook. But I am not able to post it on facebook. The video is coming from web service.
How to convert video url in nsdata and mu code is below
NSString *astrUserid=[[mutTimeline objectAtIndex:indexpath] objectForKey:#"user_id"];
NSString *astrImageid=[[mutTimeline objectAtIndex:indexpath] objectForKey:#"image_id"];
NSString *astrExt=[[mutTimeline objectAtIndex:indexpath] objectForKey:#"ext"];
NSString *aStrDisplyimage=[NSString stringWithFormat:#"http://followme.pmcommu.com/audio/user/%#-%#.%#",astrUserid, astrImageid,astrExt ];
NSURL *aimageurl=[NSURL URLWithString:aStrDisplyimage];
NSString *filePathOfVideo = [aimageurl path];
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);
}
}];
}
}];
}
I am new for that can any one help me please
or this will help you for upload and streaming video, i think
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]);
}
}];
Get the publish permission
NSArray* permissions = [[NSArray alloc] initWithObjects:
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
[permissions release];
Try this
- (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];
}
try this
[NSData dataWithContentsOfURL:[NSURL URLWithString:#"Your URL"]]
-(void)facbookSharng {
NSLog(#"Permission for sharing..%#",[FBSDKAccessToken currentAccessToken].permissions);
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"contact_email"])
{
FBSDKShareVideo *ShareVideo = [FBSDKShareVideo videoWithVideoURL:appDelegateObj.finalVideoUrl];
ShareVideo.videoURL = appDelegateObj.finalVideoUrl;
FBSDKShareVideoContent *ShareContnt = [[FBSDKShareVideoContent alloc] init];
ShareContnt.video = ShareVideo;
[FBSDKShareAPI shareWithContent:ShareContnt delegate:self]
// write the deleate methdo for post ID..
}
I am trying to get the facebook account details using SLRequest in ios.
I got all the details But Can not able to get the Profile Photo link of the User.
My code is as follow:
NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:
#"xxxxxxxxxxxxxx", ACFacebookAppIdKey,
[NSArray arrayWithObjects:#"email", nil] , ACFacebookPermissionsKey,
nil];
[_accountStore requestAccessToAccountsWithType:facebookTypeAccount
options:options
completion:^(BOOL granted, NSError *error) {
if(granted){
NSArray *accounts = [_accountStore accountsWithAccountType:facebookTypeAccount];
_facebookAccount = [accounts lastObject];
NSLog(#"Success");
[self me];
}else{
// ouch
NSLog(#"Fail");
NSLog(#"Error: %#", error);
}
}];
- (void)me{
NSURL *meurl = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *merequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:meurl
parameters:nil];
merequest.account = _facebookAccount;
[merequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *meDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", meDataString);
NSJSONSerialization *js=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
NSLog(#"%#",js);
}];
}
Help me to solve this.
You can get the user's ID from the returned response, then use the below to get the profile picture:
http://graph.facebook.com/User_ID/picture
I use SDWebImage for images:
NSString *urlstr = #"http://graph.facebook.com/100001393655684/picture";
[imageView setImageWithURL:[NSURL URLWithString:urlstr]
placeholderImage:nil];
For Twitter, please make sure you authenticate your request, check this link for more details
Note: You may need to update TWRequest to SLRequest if you aren't deploying for iOS5
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?