Post image on facebook using FBSDK 4.x for iOS - ios

For the new Facebook SDK 4.x (4.1) for iOS had new changes with the frameworks . It includes 3 different framework as like
Core
Sharing
Login.
To share any image I used FBSDKSharePhoto Class. But it has method
[FBSDKSharePhoto photoWithImage:(*UIImage) userGenerated:(BOOL)]
I want to add caption with the image as string and text. can Anyone help me for this so I can post caption with the image using FB's new sdk.
Thanks in Advance.

As #NANNAV posted it will work, but if you want to share silently with out any FB Dialog screen then use "shareWithContent" as below, but you need to submit your Facebook app for review.
Code in Obj-c
FBSDKSharePhoto *sharePhoto = [[FBSDKSharePhoto alloc] init];
sharePhoto.caption = #"Test Caption";
sharePhoto.image = [UIImage imageNamed:#"BGI.jpg"];
FBSDKSharePhotoContent *content = [[FBSDKSharePhotoContent alloc] init];
content.photos = #[sharePhoto];
[FBSDKShareAPI shareWithContent:content delegate:self];
Code in Swift
var sharePhoto = FBSDKSharePhoto()
sharePhoto.caption = "Test"
sharePhoto.image = UIImage(named: "BGI.jpg")
var content = FBSDKSharePhotoContent()
content.photos = [sharePhoto]
FBSDKShareAPI.shareWithContent(content, delegate: self)

Assign your Caption String to caption Key value
#property (nonatomic, copy) NSString *caption;
Try This :
FBSDKSharePhoto *photo = [[FBSDKSharePhoto alloc] init];
photo.image = image;
photo.userGenerated = YES;
photo.caption = #"Add Your caption";
FBSDKSharePhotoContent *content = [[FBSDKSharePhotoContent alloc] init];
content.photos = #[photo];
[FBSDKShareDialog showFromViewController:self
withContent:content
delegate:nil];

Add the below code to share text to facebook using Facebook SDK 4.x
FBSDKGraphRequestConnection *connection =[[FBSDKGraphRequestConnection alloc]init];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"Your_message_here_to_share_FB", #"message",
nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me/feed" parameters:params HTTPMethod:#"POST"];
[connection addRequest:request completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(error){
NSLog(#"Failed to share");
}
else{
NSLog(#"Updated successfully");
}
}];
*Add below code to share photo.
FBSDKGraphRequestConnection *connection =[[FBSDKGraphRequestConnection alloc]init];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys: image, #"picture",
#"Your_text_here",#"message",
nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me/photos" parameters:params HTTPMethod:#"POST"];
[connection addRequest:request completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(result)
{
NSLog(#"Posting the image is success, the result is%#",result);
}
else if(error)
{
NSLog(#"Error occured while posting image %#",error);
}
}];
[connection start];

Related

The Facebook SDK seems to be missing content title and description?

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

iOS FacebookSDK image share

I am using the following code to upload an image from my iOS to Facebook.
NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
[params setObject:#"MY TEST MSG..." forKey:#"message"];
[params setObject:UIImagePNGRepresentation(self.editImageView.image) forKey:#"picture"];
[[FBSDKGraphRequest alloc] initWithGraphPath:#"me/photos" parameters:params HTTPMethod:#"POST"] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"uploaded");
} else {
NSLog(#"Graph API Error: %#", [error description]);
}
}];
My app got stuck for couple of minutes and show the error message.
Can any one please help me?
NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:3];
UIImage *picture = FilterImage;
FbGraphFile *graph_file = [[FbGraphFile alloc] initWithImage:picture];
[variables setObject:graph_file forKey:#"file"];
[variables setObject:[NSString stringWithFormat:#"Hello testin"] forKey:#"message"];
[fbGraph doGraphPost:#"me/photos" withPostVars:variables];
NSLog(#"Now log into Facebook and look at your profile & photo albums...");

Facebook Graph Object/Event post in new 4.0 SDK

I'm attempting to post a graph event like so with the new SDK:
FBSDKAccessToken *token = [FBSDKAccessToken currentAccessToken];
FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];
NSMutableDictionary<FBGraphObject> *action = [FBGraphObject graphObject];
action[#"event"] = #"http://samples.ogp.me/680289198752391";
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me/friendlish:add" parameters:action tokenString:token.tokenString version:#"v2.3" HTTPMethod:#"POST"];
//
[connection addRequest:request completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(error)
NSLog(#"%#", error);
else
NSLog(#"%#", result);
}];
[connection start];
All works fine, and it posts -- but when I try actually changing up the example to something custom like this:
NSMutableDictionary<FBGraphObject> *action = [FBGraphObject graphObject];
NSMutableDictionary<FBGraphObject> *event = [FBGraphObject openGraphObjectForPost];
event[#"og:title"] = #"My Event";
event[#"og:type"] = #"friendlish:event";
event[#"og:url"] = #"http://www.facebook.com";
event[#"og:description"] = #"Yaba daba doo";
event[#"og:image"] = #"https://fbstatic-a.akamaihd.net/images/devsite/attachment_blank.png";
action[#"event"] = event;
I get a first error in console before the connection NSLogs are called:
Unsupported FBSDKGraphRequest attachment:{
data = {
};
"fbsdk:create_object" = 1;
"og:description" = "Yaba daba doo";
"og:image" = "https://fbstatic-a.akamaihd.net/images/devsite/attachment_blank.png";
"og:title" = "My Event";
"og:type" = "friendlish:event";
"og:url" = "http://www.facebook.com"; }, skipping.
Then the error from the connection method NSLog:
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"
UserInfo=0x174077080 {NSLocalizedDescription=unsupported URL,
NSUnderlyingError=0x17445f920 "unsupported URL"}

Is it possible to give friend request on facebook using SLRequest in ios?

I am using SLRequest to get user details and sharing on facebook and twitter. Also i am using Linkedin SDK and Google+ SDK to get user details on respective social networks. My questions are
Is it possible to give friend request on facebook using SLRequest?
Is it possible to follow a person on twitter using SLRequest?
Is it possible to connect a person on linkedin using SDK?
Is it possible to add a person on google+ using SDK?
if possible please give me a way to do that. Thanks.
After a long time, found the solution to my question,
For Facebook graph api version 2.0 does not support friend request (Refer:https://developers.facebook.com/docs/dialogs/friends/v2.0).
we can do it with twitter as follows
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if(granted) {
// Get the list of Twitter accounts.
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
// For the sake of brevity, we'll assume there is only one Twitter account present.
// You would ideally ask the user which account they want to tweet from, if there is more than one Twitter account present.
if ([accountsArray count] > 0) {
// Grab the initial Twitter account to tweet from.
ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:#"MohammadMasudRa" forKey:#"screen_name"];
[tempDict setValue:#"true" forKey:#"follow"];
NSLog(#"*******tempDict %#*******",tempDict);
//requestForServiceType
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"https://api.twitter.com/1/friendships/create.json"] parameters:tempDict];
[postRequest setAccount:twitterAccount];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *output = [NSString stringWithFormat:#"HTTP response status: %i Error %d", [urlResponse statusCode],error.code];
NSLog(#"%#error %#", output,error.description);
}];
}
}
}];
We can do it with Linkedin as follows.
NSURL *url = [NSURL URLWithString:#"http://api.linkedin.com/v1/people/~/mailbox"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
consumer:oAuthLoginView.consumer
token:oAuthLoginView.accessToken
callback:nil
signatureProvider:nil];
[request setHTTPMethod:#"POST"];
NSString *messageToPerson = #"/people/email=test123#test.com";
NSDictionary *person = [[NSDictionary alloc] initWithObjectsAndKeys:[[NSDictionary alloc] initWithObjectsAndKeys:messageToPerson,#"_path",#"test123",#"first-name",#"test",#"last-name",nil], #"person",nil];
NSArray *valueArray = [[NSArray alloc] initWithObjects:person,nil];
NSDictionary *values = [[NSDictionary alloc] initWithObjectsAndKeys:valueArray,#"values", nil];
NSDictionary *ir = [[NSDictionary alloc] initWithObjectsAndKeys:[[NSDictionary alloc] initWithObjectsAndKeys:#"friend",#"connect-type",nil], #"invitation-request",nil];
NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:values,#"recipients",#"Invitation",#"subject",#"ConnectWithMe",#"body", ir, #"item-content", nil];
[request setValue:#"json" forHTTPHeaderField:#"x-li-format"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSString *updateString = [update JSONString];
[request prepare];
[request setHTTPBodyWithString:updateString];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(postUpdateApiCallResult1:didFinish:)
didFailSelector:#selector(postUpdateApiCallResult1:didFail:) withPrepare:NO];
I unable to get details abt google plus add to circle.

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

Resources