video share on facebook - ios

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

Related

User friends are showing empty list in Facebook Sdk Graph Api v2

I have updated the version for the graph Api to v2. Now the issue I am facing is,when I executed the following code It shows me empty array :
FBRequest *friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *result, NSError *error) {
NSArray *friendshipid;
NSString *username;
if (!error) {
NSLog(#"friends = %#", [result description]);
}
if (completion) {
completion(friendshipid, username, error);
}
}];
}
}
I got to know that facebook sdk had some changes for the user friends and now It has to take the permission for the user_friends, but I have no idea where to make changes to ask for Permission for user_friends
You can use the given code snippet. Here, i have used the Classes of Social Framework to get the Facebook friends. Hope it will work for you.
- (void) connectWithFacebookFriends
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountTypeFacebook = [accountStore accountTypeWithAccountTypeIdentifier:
ACAccountTypeIdentifierFacebook];
NSDictionary *options = #{ACFacebookAppIdKey: kFaceBookId,
ACFacebookPermissionsKey: #[#"user_friends"],
ACFacebookAudienceKey: ACFacebookAudienceFriends
};
[accountStore requestAccessToAccountsWithType:accountTypeFacebook
options:options
completion:^(BOOL granted, NSError *error)
{
if(granted) {
NSArray *accounts = [accountStore
accountsWithAccountType:accountTypeFacebook];
ACAccount* facebookAccount = [accounts lastObject];
NSString *acessToken = [NSString stringWithFormat:#"%#",facebookAccount.credential.oauthToken];
NSDictionary *parameters = #{#"access_token": acessToken};
NSURL *feedURL = [NSURL URLWithString:#"https://graph.facebook.com/me/friends"];
SLRequest *feedRequest =
[SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:feedURL
parameters:parameters];
[feedRequest performRequestWithHandler:^(NSData *responseData,
NSHTTPURLResponse *urlResponse, NSError *error)
{
NSString * str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
DLog(#"%#",str);
NSLog(#"Request failed, %#", [urlResponse description]);
}];
} else {
NSLog(#"Access Denied");
NSLog(#"[%#]",[error localizedDescription]);
}
}];
}

Login and list Facebook friends using Social Framework

Could someone give me some pointers on how to integrate this? my goal is to get list of friends who installed my app (fb app). initially I need to login user to my app first and list friends who have / haven't installed the app.
PS : I don't want to use Facebook SDK. I had nightmares in the past due to facebook did countless time changing the sdk.
===========
UPDATE
I've successfully login and list my facebook friends. But now problem to list my friend who have the app and list picture as well. I tried this :
URL : https://graph.facebook.com/me/friends?friends?fields=id,name,installed,picture
which give me OAuthException : An active access token must be used to query information about the current user. problem.
I tried also in API Graph, it works without mentioned error.
if I try only me/friends works perfectly, it will list down all my friends.
First import Social, Account, SystemConfiguration framework in your project.
Then use this code on your.m file
-(void)facebook
{
self.accountStore = [[ACAccountStore alloc]init];
ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSString *key = #"XXXXXXXXXXXXX";//get your key form creating new app in facebook app section
NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:key,ACFacebookAppIdKey,#[#"email"],ACFacebookPermissionsKey, nil];
[self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
^(BOOL granted, NSError *e) {
if (granted)
{
NSArray *accounts = [self.accountStore accountsWithAccountType:FBaccountType];
//it will always be the last object with single sign on
self.facebookAccount = [accounts lastObject];
ACAccountCredential *facebookCredential = [self.facebookAccount credential];
NSString *accessToken = [facebookCredential oauthToken];
NSLog(#"Facebook Access Token: %#", accessToken);
NSLog(#"facebook account =%#",self.facebookAccount);
[self get];
[self getFBFriends];
isFacebookAvailable = 1;
} else
{
//Fail gracefully...
NSLog(#"error getting permission yupeeeeeee %#",e);
sleep(10);
NSLog(#"awake from sleep");
isFacebookAvailable = 0;
}
}];
}
-(void)get
{
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodGET URL:requestURL parameters:nil];
request.account = self.facebookAccount;
[request performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *response, NSError *error) {
if(!error)
{
NSDictionary *list =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"Dictionary contains: %#", list );
fbID = [NSString stringWithFormat:#"%#", [list objectForKey:#"id"]];
globalFBID = fbID;
gender = [NSString stringWithFormat:#"%#", [list objectForKey:#"gender"]];
playerGender = [NSString stringWithFormat:#"%#", gender];
NSLog(#"Gender : %#", playerGender);
self.globalmailID = [NSString stringWithFormat:#"%#",[list objectForKey:#"email"]];
NSLog(#"global mail ID : %#",globalmailID);
fbname = [NSString stringWithFormat:#"%#",[list objectForKey:#"name"]];
NSLog(#"faceboooookkkk name %#",fbname);
if([list objectForKey:#"error"]!=nil)
{
[self attemptRenewCredentials];
}
dispatch_async(dispatch_get_main_queue(),^{
});
}
else
{
//handle error gracefully
NSLog(#"error from get%#",error);
//attempt to revalidate credentials
}
}];
self.accountStore = [[ACAccountStore alloc]init];
ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSString *key = #"451805654875339";
NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:key,ACFacebookAppIdKey,#[#"friends_videos"],ACFacebookPermissionsKey, nil];
[self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
^(BOOL granted, NSError *e) {}];
}
-(void)getFBFriends
{
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/me/friends"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodGET URL:requestURL parameters:nil];
request.account = self.facebookAccount;
[request performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *response, NSError *error) {
if(!error)
{
NSDictionary *friendslist =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
for (id facebookFriendList in [friendslist objectForKey:#"data"])
{
NSDictionary *friendList = (NSDictionary *)facebookFriendList;
[facebookFriendIDArray addObject:[friendList objectForKey:#"id"]];
}
if([friendslist objectForKey:#"error"]!=nil)
{
[self attemptRenewCredentials];
}
dispatch_async(dispatch_get_main_queue(),^{
});
}
else
{
//handle error gracefully
NSLog(#"error from get%#",error);
//attempt to revalidate credentials
}
}];
self.accountStore = [[ACAccountStore alloc]init];
ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSString *key = #"451805654875339";
NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:key,ACFacebookAppIdKey,#[#"friends_videos"],ACFacebookPermissionsKey, nil];
[self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
^(BOOL granted, NSError *e) {}];
}
-(void)accountChanged:(NSNotification *)notification
{
[self attemptRenewCredentials];
}
-(void)attemptRenewCredentials
{
[self.accountStore renewCredentialsForAccount:(ACAccount *)self.facebookAccount completion:^(ACAccountCredentialRenewResult renewResult, NSError *error){
if(!error)
{
switch (renewResult) {
case ACAccountCredentialRenewResultRenewed:
NSLog(#"Good to go");
[self get];
break;
case ACAccountCredentialRenewResultRejected:
NSLog(#"User declined permission");
break;
case ACAccountCredentialRenewResultFailed:
NSLog(#"non-user-initiated cancel, you may attempt to retry");
break;
default:
break;
}
}
else{
//handle error gracefully
NSLog(#"error from renew credentials%#",error);
}
}];
}
I finally got it, apparently you cannot append inside the URL. you need to pass the fields in parameter inside SLRequest
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/me/friends"];
NSDictionary *param=[NSDictionary dictionaryWithObjectsAndKeys:#"picture,id,name,installed",#"fields", nil];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:requestURL
parameters:param];

How to upload/share video on Facebook ?

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

Reading information from Facebook

I am a beginner in iOS. I am trying to create an app and referred a lot of posts in the stackoverflow and some other sites and i used the following code to access the Facebook account.
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (appDelegate.session.isOpen) {
[appDelegate.session closeAndClearTokenInformation];
} else {
if (appDelegate.session.state != FBSessionStateCreated) {
appDelegate.session = [[FBSession alloc] init];
}
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
}];
}
After that in a function i used the following code to access the Facebook details of the user.
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
_FirstName.text = user.first_name;
regisrationdetails.fbid = user.id;
_LastName.text=user.last_name;
_EmailAddress.text=user.email;
NSArray *locationarray=[[NSArray alloc]initWithObjects:user.location,nil];
_City.text=[locationarray objectAtIndex:1];
NSLog(#"%#",user.first_name);
}
}];
No error is being shown but i can't get the information from Facebook the the text fields.If anyone good at this knows how to access the information then please help me out.
- (IBAction)getMeButtonTapped:(id)sender {
if(!_accountStore)
_accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookTypeAccount = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[_accountStore requestAccessToAccountsWithType:facebookTypeAccount
options:#{ACFacebookAppIdKey: #"571438296262222", ACFacebookPermissionsKey: #[#"email"]}
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 localizedDescription]);
}
}];
}
- (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);
}];}
Use this hope this helps you, also add social framework as well as Accounts Framework
try this..
- (void)fetchFacebookUserInfo {
if ( FBSession.activeSession.isOpen) {
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error) {
if (!error) {
NSString *name = user.name;
NSString *userName = user.username;
NSString *firstName = user.first_name;
NSString *lastName = user.last_name;
NSString *email1 = [user objectForKey:#"email"];
NSString *birthday1 = user.birthday;
NSString *locale = [user objectForKey:#"locale"];
NSString *location = [user.location objectForKey:#"name"];
}
}];
}

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?

Resources