In my iphone app i want to post photos to selected facebook contacts. I'm getting that photos from phone library.
I'm using this code:
fbString=[NSString stringWithFormat:#"%#\n%#",appdelegate.titleString,appdelegate.descriptionString];
NSArray *permissions =[NSArray arrayWithObjects:#"publish_actions",#"publish_stream",#"manage_friendlists", nil];
NSData* imageData = UIImageJPEGRepresentation(self.img, 90);
NSLog(#"imageData %#",imageData);
NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:fbString, #"message",imageData,#"source",nil];
NSLog(#"fbid count %d",fbidarray.count);
[[FBSession activeSession] reauthorizeWithPublishPermissions:permissions
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error)
{
if (!error) {
for(int j=0;j<fbidarray.count;j++)
{
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%#/photos",[fbidarray objectAtIndex:j]] parameters:params HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error1)
{
NSLog(#"errors in the view %#",error1);
if(!error1 )
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Success"
message:[NSString stringWithFormat:#" Sucessfully posted "]
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
}];
}
}
}];
You can try this :
NSMutableDictionary *postTest = [[NSMutableDictionary alloc]init];
[postTest setObject:[NSString stringWithFormat#"Your message"] forKey:#"message"];
[postTest setObject:#"" forKey:#"picture"];
[postTest setObject:#"" forKey:#"name"];
[postTest setObject:#"APPID" forKey:#"app_id"];
NSString *userFBID =[NSString stringWithFormat:#"%#",[allInfoDict objectForKey:#"Friends facebook ID "]];
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%#/feed?access_token=%#",userFBID,[appDelegate.mysession accessToken]]
parameters:postTest
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
NSDictionary * result,
NSError *error) {
if (error) {
[self hideHUD];
NSLog(#"Error: %#", [error localizedDescription]);
} else {
// Success
}
}];
[postTest release];
Related
I don't want to use graph story. But all other methods are rejected by Facebook team with message: Please make sure you are not pre-filling message field.
for example:
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:text forKey:#"message"];
[params setObject:#"link" forKey:#"type"];
//[params setObject:#"http://google.com/" forKey:#"link"];
if(photoID) {
[params setObject:photoID forKey:#"object_attachment"];
}
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
NSMutableDictionary* photosParams = [NSMutableDictionary dictionaryWithObjectsAndKeys:
image,#"source",
text,#"message",
nil];
FBRequest *request = [[FBRequest alloc] initWithSession:[FBSession activeSession]
graphPath:#"me/photos"
parameters:photosParams
HTTPMethod:#"POST"];
[connection addRequest:request completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
completionBlock(error);
}];
FBRequest *req = [FBRequest requestForGraphPath:#"me/feed"];
req.graphObject = (id<FBGraphObject>)[NSDictionary dictionaryWithDictionary:params];
[connection addRequest:req
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error && result) {
NSLog(#"%#",result);
}
}
];
Please explain what method I should use in this case?
In case if correct behavior is use stories then why other methods are not marked as deprecated?
Thanks.
I add the function working well on iOS6, but with iOS7, I had to update Facebook SDK because id and setId from the old ones are marked as non-public and are'nt validated.
So, I replaced the old SDK by the new one but, of course, the post image is no more working (as the id is certainly unknown).
I had this :
[params setObject:textViewMessageFacebook.text forKey:#"message"];
[params setObject:UIImagePNGRepresentation(screenshot) forKey:#"picture"];
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%#/photos", idAmiS]
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error)
but don't know how to correct it to have it working...
Thanks
Use SlComposer Controller to post image on facebook.
1) first you add the Social framework and Account framewok into your project and then try below code
writ this code where you want...
{
ACAccountType *facebookTypeAccount = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[accountStore requestAccessToAccountsWithType:facebookTypeAccount
options:#{ACFacebookAppIdKey: #"131740927031850", ACFacebookPermissionsKey: #[#"email"]}
completion:^(BOOL granted, NSError *error) {
if(granted){
NSArray *accounts = [accountStore accountsWithAccountType:facebookTypeAccount];
_facebookAccount = [accounts lastObject];
ACAccountCredential *fbCredential = [_facebookAccount credential];
accessToken = [fbCredential oauthToken];
NSLog(#"Facebook Access Token: %#", accessToken);
NSLog(#"Success");
[self facebook];
}else{
NSLog(#"Fail");
NSLog(#"Error: %#", error);
}
}];
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
SLComposeViewController *tweetSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[tweetSheet setInitialText:#"posting from my own app! :)"];
[tweetSheet addURL:[NSURL URLWithString:#"www.xyz.com"]];
// Here you add the image
[tweetSheet addImage:[UIImage imageNamed:#"yourimage.png"]];
[self presentViewController:tweetSheet animated:YES completion:nil];
}
else
{
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Sorry"
message:#"You can't send a tweet right now, make sure your device has an internet connection and you have at least one Twitter account setup"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
- (void)facebook
{
NSURL *meurl = [NSURL URLWithString:#"https://graph.facebook.com/me"];
NSLog(#"URl:-%#",meurl);
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(#"Parsed Data:-%#", meDataString);
}];
}
I am trying to upload a video from my iPhone to Facebook. I have logged in using FBLoginView and created a FBSession. I have used the following code to initiate a FBRequest of upload the video.
- (void)buttonRequestClickHandler:(id)sender {
if (FBSession.activeSession.isOpen) {
[FBSession.activeSession requestNewPublishPermissions:permissions
defaultAudience:FBSessionDefaultAudienceOnlyMe
completionHandler:nil];
NSString *audioName = [pictureDictionary4 objectForKey:#"photoVideokey"];
NSArray *pathsa = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectorya = [pathsa objectAtIndex:0];
NSString *moviePath = [documentsDirectorya stringByAppendingPathComponent:#"/Movie"];
NSString *fullPatha = [moviePath stringByAppendingPathComponent:audioName];
NSURL *pathURL = [[NSURL alloc]initFileURLWithPath:fullPatha isDirectory:NO];
NSData *videoData = [NSData dataWithContentsOfFile:fullPatha];
NSString *titleString = self.videotitle.text;
NSString *descripString = self.descrp.text;
NSDictionary *videoObject = #{
#"title":titleString,
#"description": descripString,
[pathURL absoluteString]: videoData
};
FBRequest *uploadRequest = [FBRequest requestWithGraphPath:#"me/videos"
parameters:videoObject
HTTPMethod:#"POST"];
[uploadRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error)
NSLog(#"Done: %#", result);
else
NSLog(#"Error: %#", error.localizedDescription);
}];
}
I get an error
Error: The operation couldn’t be completed. (com.facebook.sdk error 5.)
I'm not sure what the error pertains to:
I know I'm logged in
I don't know if I am getting connected but I am on internet with iPhone
Are my parameters incorrect?
I have been messing with this for HOURS with no results
Any help from anyone/everyone would be greatly appreciated.
Finally got this working by going into my iPhone settings-facebook and deleting my account. Then when I tapped to upload the video in my app it loaded a view that asked if Facebook could use my app and I said yes then bam it uploaded. Also had to change my permissions to just publish_actions and get rid of publish_streams since that is a read permission. Anyway it is working now. Next to get defaultAudience to load from a string picked by user and not hard coded. Another post.
I guess its something to do with stream publishing permission. Try this way. It worked for me. I was using Facebook SDK 3.8.0
[self performPublishAction:^{
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"faisal" ofType:#"mov"];
NSURL *pathURL = [[NSURL alloc]initFileURLWithPath:filePath isDirectory:NO];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *videoObject = #{
#"title": #"This is my title",
#"description": #"This is my description",
[pathURL absoluteString]: videoData
};
FBRequest *uploadRequest = [FBRequest requestWithGraphPath:#"me/videos"
parameters:videoObject
HTTPMethod:#"POST"];
[uploadRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error)
NSLog(#"Done: %#", result);
else
NSLog(#"Error: %#", error.localizedDescription);
}];
}];
and
- (void) performPublishAction:(void (^)(void)) action {
if ([FBSession.activeSession.permissions indexOfObject:#"publish_stream"] == NSNotFound) {
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_stream"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
} else if (error.fberrorCategory != FBErrorCategoryUserCancelled){
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Permission denied"
message:#"Unable to get permission to post"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}];
} else {
action();
}
}
This Code is Tested successfully 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);
}
}];
}
}];
}
}
And I GOT Error:
The operation couldn’t be completed. (com.facebook.sdk error 5.)
It happens when facebook is being inited. Next time i open my app, it works fine, its always the first time. Tried everything in app, but it seems to be on the Facebook SDK side.
Few causes for seeing com.facebook.sdk error 5:
Session is is not open. Validate.
Facebook has detected that you're spamming the system. Change video name.
Facebook has a defined limit using the SDK. Try a different app.
Wrong publish permission. Give publish_actions a spin.
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
photoDescription, #"message",
image, #"image",
nil];
[facebook requestWithGraphPath:#"me/photos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
This is what I did to upload a image to Facebook. The image is uploaded successfully to FaceBook 'photos'. But I want to post the image to my FaceBook Feed. So i tried,
[facebook requestWithGraphPath:#"me/feed"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
but it still the images posted to the 'photos'. It does not appear in the Feed...
I searched and used different methods for a solution, but I couldn't find anything helpful...
Not sure what your params looks like, but try this..
UIImage *image = ...// some image.
NSData *imageData= UIImagePNGRepresentation(image);
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"some message", #"message", imageData,#"source", nil];
[facebook dialog:#"feed" andParams:params andDelegate:self];
UIImage* image=...;
if ([FBSession.activeSession.permissions
indexOfObject:#"publish_actions"] == NSNotFound) {
NSArray *permissions =
[NSArray arrayWithObjects:#"publish_actions",#"publish_stream", nil];
[[FBSession activeSession] requestNewPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {}];
}
else
{
NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
[params setObject:#"Photo post test..." forKey:#"message"];
[params setObject:UIImagePNGRepresentation(image) forKey:#"picture"];
//for not allowing multiple hits
[FBRequestConnection startWithGraphPath:#"me/photos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error)
{
if (error)
{
//showing an alert for failure
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Post Failed"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
else
{
//showing an alert for success
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Post success"
message:#"Shared the photo successfully"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}];
}
in iPhone App how to post Youtube video link using facebook graph Api to FaceBook Wall post?
You can try this :
-(IBAction)postMeFeedButtonPressed:(id)sender {
NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:4];
[variables setObject:#"#Your Message" forKey:#"message"];
[variables setObject:#"#http://Your Youtube Link" forKey:#"link"];
[variables setObject:#"#This is the bolded copy next to the image" forKey:#"name"];
[variables setObject:#"#This is the plain text copy next to the image. All work and no play makes Jack a dull boy." forKey:#"description"];
FbGraphResponse *fb_graph_response = [fbGraph doGraphPost:#"me/feed" withPostVars:variables];
NSLog(#"postMeFeedButtonPressed: %#", fb_graph_response.htmlResponse);
//parse our json
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *facebook_response = [parser objectWithString:fb_graph_response.htmlResponse error:nil];
[parser release];
//let's save the 'id' Facebook gives us so we can delete it if the user presses the 'delete /me/feed button'
self.feedPostId = (NSString *)[facebook_response objectForKey:#"id"];
NSLog(#"feedPostId, %#", feedPostId);
NSLog(#"Now log into Facebook and look at your profile...");
}
Try this to post youtube video
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[accountStore requestAccessToAccountsWithType:accountType options:#{ACFacebookAppIdKey : facebookAppKey, ACFacebookPermissionsKey : [NSArray arrayWithObjects:#"publish_stream", nil], ACFacebookAudienceKey : ACFacebookAudienceOnlyMe} completion:^(BOOL granted, NSError *error) {
if(granted ) {
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
NSDictionary *postDict = #{
#"link": youtubeurl,//URL of youtube video
};
ACAccount *facebookAccount = [accountsArray objectAtIndex:0];
SLRequest *facebookRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:[NSURL URLWithString:#"https://graph.facebook.com/me/feed"]
parameters:postDict];
[facebookRequest setAccount:facebookAccount];
[facebookRequest performRequestWithHandler:^( NSData* responseData, NSHTTPURLResponse* urlResponse, NSError* error ) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.view setUserInteractionEnabled:true];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Posted Successfully on Facebook" message:#"" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
});
}];
} else {
NSLog(#"Error %#", error.description);
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Account not found" message:#"Please log in to Facebook account from Settings" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
});
}
}];