Facebook Share Dialog in iOS - ios

I am trying to implement the native Share dialog from Facebook in a sample application.
Seem to have some problem in doing so.
Things I have done so far:
Included the latest Facebook SDK
Included the AdSupport, Social, Account, Security and libsqlite3.dylib.
Added the sample code from Facebook.
Added -lsqlite3.0 -ObjC to Other Linker Flags as well
Added the app id to the plist
Added the FBUserSettingsViewResources bundle and FacebookSDKResources.bundle to the project
But I can't seem to share the URL. The share dialog doesn't even appear.
My code looks like this:
Viewcontroller.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{
IBOutlet UIButton *buttonShare;
}
- (IBAction)shareButtonClicked:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#import <FacebookSDK/FacebookSDK.h>
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)shareButtonClicked:(id)sender
{
FBShareDialogParams *params = [[FBShareDialogParams alloc] init];
params.link = [NSURL URLWithString:#"https://developers.facebook.com/ios"];
params.picture = [NSURL URLWithString:#"https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png"];
params.name = #"Facebook SDK for iOS";
params.caption = #"Build great apps";
[FBDialogs presentShareDialogWithParams:params clientState:nil handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if(error) {
NSLog(#"Error: %#", error.description);
} else {
NSLog(#"Success!");
}
}];
}
#end
Not able to share the URL. Need some guidance on this.

- (IBAction)shareButtonClicked:(id)sender
{
// if the session is closed, then we open it here, and establish a handler for state changes
[FBSession openActiveSessionWithReadPermissions:nil allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState state, NSError *error)
{
if (error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else if(session.isOpen)
{
NSString *str_img = [NSString stringWithFormat:#"https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png"];
NSDictionary *params = #{
#"name" :[NSString stringWithFormat:#"Facebook SDK for iOS"],
#"caption" : #"Build great Apps",
#"description" :#"Welcome to iOS world",
#"picture" : str_img,
#"link" : #"",
};
// Invoke the dialog
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:params
handler:
^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
//NSLog(#"Error publishing story.");
[self.indicator stopAnimating];
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
//NSLog(#"User canceled story publishing.");
[self.indicator stopAnimating];
} else {
//NSLog(#"Story published.");
[self.indicator stopAnimating];
}
}}];
}
}];
return;
}

Do you have Facebook App installed on your device? The Share dialog only works if you have the Facebook app installed.
From the Share dialog documentation :
Tip 1: What if people don't have the Facebook app installed?
The Share dialog can't be displayed if people don't have the Facebook app installed. Apps can detect this by calling [FBDialogs canPresentShareDialogWithParams:nil]; and may disable or hide a sharing button or fall back to the Feed dialog to share on the web. See the HelloFacebookSample included with the iOS SDK for an example.
From what I saw, iOS 6 will return NO for + canPresentShareDialogWithParams:. It only responds to + canPresentOSIntegratedShareDialogWithSession:. But I could be wrong here.
Anyways, this is how I do it -
1. For sharing links :
if ([FBDialogs canPresentShareDialogWithParams:nil]) {
NSURL* url = [NSURL URLWithString:link.url];
[FBDialogs presentShareDialogWithLink:url
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if(error) {
NSLog(#"Error: %#", error.description);
} else {
NSLog(#"Success");
}
}];
}
2.For OpenGraph calls :
id<FBGraphObject> pictureObject =
[FBGraphObject openGraphObjectForPostWithType:#"your_namespace:picture"
title:image.title
image:image.thumbnailUrl
url:image.url
description:#""];
id<FBOpenGraphAction> action = (id<FBOpenGraphAction>)[FBGraphObject graphObject];
[action setObject:pictureObject forKey:#"picture"];
[FBDialogs presentShareDialogWithOpenGraphAction:action
actionType:#"your_namespace:action_name"
previewPropertyName:#"picture"
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if(error) {
NSLog(#"Error: %#", error.description);
} else {
NSLog(#"Success");
}
}];
Check out other ways to share on iOS here
Hope this helps.

This works for me:
NSString *url = #"myUrl";
FBLinkShareParams* params = [[FBLinkShareParams alloc]init];
params.link = [NSURL URLWithString:url];
if([FBDialogs canPresentShareDialogWithParams:params]){
[FBDialogs presentShareDialogWithLink: [NSURL URLWithString:url]
name: #"Name"
caption: #"Caption"
description: #"Description"
picture: nil
clientState: nil
handler: nil];
}
else{
[...]
}

- (IBAction)btn_facebook:(id)sender {
[self performSelector:#selector(fb_func) withObject:nil afterDelay:0.0];
}
-(void)fb_func
{
// if the session is closed, then we open it here, and establish a handler for state changes
[FBSession openActiveSessionWithReadPermissions:nil allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState state, NSError *error)
{
if (error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else if(session.isOpen)
{
NSString *str_link = #"";
NSLog(#"%#",str_link);
NSDictionary *params = #{
#"name" :#"name",
#"caption" : #"Description",
#"description" :#"test",
#"picture" : PostimageToPintresrAndFacebook,
#"link" : #"url",
};
// Invoke the dialog
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:params
handler:
^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
NSLog(#"Error publishing story.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
NSLog(#"User canceled story publishing.");
} else {
NSLog(#"Story published.");
}
}}];
}
}];
return;
}

Related

Fb share dialog, can i simply post a picture with a description?

I'm trying to create a simple sharing function for my ios app. I wanna take advantage of the new sharing dialog (advantages like , tagging friends, add places,ecc..). What i wanna share is a photo ,a link to itunes app download, a description that comes from the ios app. I have tried the sharedialog, something like this:
NSURL *url=[[NSURL alloc] initWithString:#"https://itunes.apple.com/it/app/myapplication"];
[FBDialogs presentShareDialogWithLink:url name:#"My app name" caption:#"" description:#"prefilled descriptiontest" picture:[NSURL URLWithString:#"http://www.example.com/image.jpg"] clientState:nil handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if(error) {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
UIAlertView *av = [[[UIAlertView alloc]
initWithTitle:#"Sorry :("
message:#"There's been a problem publishing your message. Please try again!"
delegate:self
cancelButtonTitle:#"Close"
otherButtonTitles:nil] autorelease];
[av show];
} else {
// Success
UIAlertView *av = [[[UIAlertView alloc]
initWithTitle:#"Published!"
message:#"Your post has been successfully published."
delegate:self
cancelButtonTitle:#"Close"
otherButtonTitles:nil] autorelease];
[av show];
}
}];
It works but i see my prefilled description only in share dialog, when i see the shared content on facebook i only see the description taken from the linked page. So i have tried this other solution, the photodialog :
UIImage *Image=[UIImage imageNamed:#"myphoto.jpg"];
// Open the image picker and set this class as the delegate
FBPhotoParams *params = [[FBPhotoParams alloc] init];
// Note that params.photos can be an array of images. In this example
// we only use a single image, wrapped in an array.
params.photos = #[Image];
[FBDialogs presentShareDialogWithPhotoParams:params
clientState:nil
handler:^(FBAppCall *call,
NSDictionary *results,
NSError *error) {
if (error) {
NSLog(#"Error: %#",
error.description);
} else {
NSLog(#"Success!");
}
}];
In this way i can post a photo on my wall but the description parameter seems to be onlyread and i can't set any prefilled text. How i can do? There's a way to force the visualization of my description text in the sharelink dialog? Or there's a way to set a text in the photodialog? Or there another solution ?
The only solution seems to be to use only the web fallback:
NSMutableDictionary *parameter = [NSMutableDictionary dictionaryWithObjectsAndKeys:
name, #"name",
author, #"caption",
linkShare, #"link",
userImage, #"picture",
nil];
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:parameter
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error)
{
NSLog(#"Error publishing story: %#", error.description);
}
else
{
if (result == FBWebDialogResultDialogNotCompleted)
{
NSLog(#"User cancelled.");
}
else
{
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
NSLog(#"User login");
if (![urlParams valueForKey:#"post_id"])
{
NSLog(#"User cancelled post.");
}
else
{
NSString *result = [NSString stringWithFormat: #"Posted story, id: %#", [urlParams valueForKey:#"post_id"]];
NSLog(#"result %#", result);
}
}
}
}];

Share app through facebook is not working

Hi in my Application i have option of sharing my application through Facebook. So I have added the Facebook framework to my project and I have added the bundle id into my Facebook and got the App id but the problem is I'm not Unable to share the App its showing like this.
An error occurred. Please try again later
In my Stimulator is showing like this i don't why it's showing like that. If my device have Facebook App its working fine but if it doesn't have the Facebook App its showing error like this. Please tell how to resolve this issue.
- (IBAction)share:(id)sender {
FBLinkShareParams *params = [[FBLinkShareParams alloc] init];
params.link = [NSURL URLWithString:#"url/"];
// If the Facebook app is installed and we can present the share dialog
if ([FBDialogs canPresentShareDialogWithParams:params]) {
// Present share dialog
[FBDialogs presentShareDialogWithLink:params.link
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if(error) {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
NSLog(#"Error publishing story: %#", error.description);
} else {
// Success
NSLog(#"result %#", results);
}
}];
// If the Facebook app is NOT installed and we can't present the share dialog
} else {
// FALLBACK: publish just a link using the Feed dialog
// Put together the dialog parameters
// Put together the dialog parameters
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"My appname", #"name",
#"test share.", #"caption",
#"sample.", #"description",
#"myrul", #"link",
nil];
// Show the feed dialog
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
NSLog(#"Error publishing story: %#", error.description);
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// User canceled.
NSLog(#"User cancelled.");
} else {
// Handle the publish feed callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"post_id"]) {
// User canceled.
NSLog(#"User cancelled.");
} else {
// User clicked the Share button
NSString *result = [NSString stringWithFormat: #"Posted story, id: %#", [urlParams valueForKey:#"post_id"]];
NSLog(#"result %#", result);
}
}
}
}];
}
}
- (NSDictionary*)parseURLParams:(NSString *)query {
NSArray *pairs = [query componentsSeparatedByString:#"&"];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
for (NSString *pair in pairs) {
NSArray *kv = [pair componentsSeparatedByString:#"="];
NSString *val =
[kv[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
params[kv[0]] = val;
}
return params;
}
I have used the above code for its not working please help me how to resolve this issue.
Thanks.
Use this code for Share App.
-(void)facebook
{
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(#"Cancelled");
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Congratulations!" message:#"Successfully posted to facebook Wall." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
[Flurry logEvent:#"Share screen - Successfully posted on Facebook"];
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
NSString *str=[NSString stringWithFormat:#" I am using App for my iPhone. You too can download it from here"];
[controller setInitialText:str];
[self presentViewController:controller animated:YES completion:Nil];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry!"message:#"Please add Facebook account in settings menu" delegate:self cancelButtonTitle:Nil otherButtonTitles:#"Ok", nil];
alert.tag=100;
[alert show];
}
}
For use of SLComposeViewController,you have to add Social Framework. It fetch your facebook account from setting and you can share your app link through SLComposeViewController. and
if you want to add images or URL to in than :
[composeController addImage:[UIImage imageNamed:#"image.png"]];
[composeController addURL: [NSURL URLWithString:#"apple.com"]];

Why my dialogue box login of the Facebook integration isn't supported?

In my App, I've created Facebook Integration when I click on Facebook login it goes to Safari browser, how can change it to dialogue box login without entering via Safari web browser?
Thanks In Advance.
[FBSession.activeSession closeAndClearTokenInformation];
if (FBSession.activeSession.accessTokenData.loginType != FBSessionLoginTypeFacebookApplication /||
FBSession.activeSession.accessTokenData.loginType !=
FBSessionLoginTypeSystemAccount/) {
[HUD hide:YES];
HUD = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
HUD.labelText = #"Signing In";
[FBSession openActiveSessionWithReadPermissions:#[#"basic_info",#"email",#"user_location",#"user_birthday",#"user_hometown,user_friends"]
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
switch (state) {
case FBSessionStateOpen:{
[FBSession setActiveSession:session];
[self checkSessionState:state];
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection
*connection, NSDictionary *user, NSError *error) {
if (error) {
[HUD hide:YES];
NSLog(#"error Report :%#",error);
}
else
{
[HUD hide:YES];
NSString *userLocation = [NSString stringWithFormat:#"%#\n\n",user.location[#"name"]];
NSArray* foo = [userLocation componentsSeparatedByString: #","];
NSString *strCity = [foo objectAtIndex: 0];
NSString *strState = [foo objectAtIndex: 1];
NSString *linkURL = [NSString stringWithFormat:#"http://carzillaapp.com/"];
NSString *pictureURL = #"http://www.friendsmash.com/images/logo_large.jpg";
// NSString *pictureURL = #" ";
// Prepare the native share dialog parameters
FBShareDialogParams *shareParams = [[FBShareDialogParams alloc] init];
shareParams.link = [NSURL URLWithString:linkURL];
shareParams.name = #"Download and Checkout CarZilla App!";
shareParams.caption= #"An online Car Showroom!";
shareParams.picture= [NSURL URLWithString:pictureURL];
shareParams.description =
[NSString stringWithFormat:#"Both new and old cars available there!"];
if ([FBDialogs canPresentShareDialogWithParams:shareParams]){
[FBDialogs presentShareDialogWithParams:shareParams
clientState:nil
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if(error) {
NSLog(#"Error publishing story.");
} else if (results[#"completionGesture"] &&
[results[#"completionGesture"] isEqualToString:#"cancel"]) {
NSLog(#"User canceled story publishing.");
} else {
NSLog(#"Story published.");
}
}];
} else {
// Prepare the web dialog parameters
NSDictionary *params = #{
#"name" : shareParams.name,
#"caption" : shareParams.caption,
#"description" : shareParams.description,
#"picture" : pictureURL,
#"link" : linkURL
};
// Invoke the dialog
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:params
handler:
^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
NSLog(#"Error publishing story.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
NSLog(#"User canceled story publishing.");
} else {
NSLog(#"Story published.");
}
}}];
}
NSDictionary *params = #{
#"name" : shareParams.name,
#"caption" : shareParams.caption,
#"description" : shareParams.description,
#"picture" : pictureURL,
#"link" : linkURL
};
[FBWebDialogs presentRequestsDialogModallyWithSession:nil
message:[NSString stringWithFormat:#"Checkout the CarZilla App!"]
title:#"Invite"
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error)
{
if (error) {
// Case A: Error launching the dialog or sending request.
NSLog(#"Error sending request.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// Case B: User clicked the "x" icon
NSLog(#"User canceled request.");
} else {
NSLog(#"Request Sent.");
}
}}
];
SignUpViewController *faceblogin = [[SignUpViewController alloc]init];
faceblogin.firstName = [NSString stringWithFormat:#"%# ",user.first_name];
faceblogin.lastName = user.last_name;
faceblogin.email =[user objectForKey:#"email"];
faceblogin.city = strCity;
faceblogin.state = strState;
faceblogin.fblogin = YES;
fbFailure = YES;
fbMsg = YES;
faceblogin.accountType = #"Individual Buyer/Seller";
//faceblogin.isPhoneno = YES;
[self presentViewController:faceblogin animated:YES completion:nil];
}
}];
break;
}
case FBSessionStateClosed:{
[HUD hide:YES];
NSLog(#"facebook values");
}
case FBSessionStateClosedLoginFailed:{
[HUD hide:YES];
if ((!fbFailure && fbMsg) || error.code == 2) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Unfortunately, we
were not able to log you in using your Facebook credentials."
delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
fbMsg = NO;
[alert show];
}
[FBSession.activeSession closeAndClearTokenInformation];
break;
}
default:
break;
}
} ];
}
else{
NSLog(#"accounts"); }

FBSession: an attempt was made reauthorize permissions on an unopened session in ios

Hi I am using facebook SDK 3.8 in my project. and using HelloFaceBookSample Code in my app but in my app i have no login button of facebook. I have implemented login flow of facebook and after login i have post on facebook. Now Post Status working fine but when i post image on facebook it give me error of
an attempt was made reauthorize permissions on an unopened session in ios
Code :
-(void) clickButtonFacebookUsingSDK
{
if (!appdelegate.session.isOpen)
{
appdelegate.session = [[FBSession alloc] init];
[appdelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if(appdelegate.session.isOpen)
{
NSLog(#"calling postdata when session is not open******");
[self postData];
}
}];
}
else
{
NSLog(#"calling postdata when session is open******");
[self postData];
}
}
-(void) postData
{
[self showingActivityIndicator];
UIImage *img = [UIImage imageNamed:#"abc.jpg"];
[self performPublishAction:^{
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
connection.errorBehavior = FBRequestConnectionErrorBehaviorReconnectSession
| FBRequestConnectionErrorBehaviorAlertUser
| FBRequestConnectionErrorBehaviorRetry;
FBRequest *req = [FBRequest requestForUploadPhoto:img];
[req.parameters addEntriesFromDictionary:[NSMutableDictionary dictionaryWithObjectsAndKeys:message3, #"message", nil]];
[connection addRequest:req
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
// [self showAlert:#"Photo Post" result:result error:error];
[self showAlert:#"Photo Post" result:result resulterror:error];
if (FBSession.activeSession.isOpen) {
}
}];
[connection start];
}];
}
- (void) performPublishAction:(void (^)(void)) action {
// we defer request for permission to post to the moment of post, then we check for the permission
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound)
{
// if we don't already have the permission, then we request it now
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_actions"]
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();
}
}
// UIAlertView helper for post buttons
- (void)showAlert:(NSString *)message result:(id)result resulterror:(NSError *)error
{
NSString *alertMsg;
NSString *alertTitle;
if (error)
{
alertTitle = #"Error";
// Since we use FBRequestConnectionErrorBehaviorAlertUser,
// we do not need to surface our own alert view if there is an
// an fberrorUserMessage unless the session is closed.
if (FBSession.activeSession.isOpen) {
alertTitle = #"Error";
} else {
// Otherwise, use a general "connection problem" message.
alertMsg = #"Operation failed due to a connection problem, retry later.";
}
}
else
{
NSDictionary *resultDict = (NSDictionary *)result;
alertMsg = [NSString stringWithFormat:#"Successfully posted '%#'.", message];
NSString *postId = [resultDict valueForKey:#"id"];
if (!postId) {
postId = [resultDict valueForKey:#"postId"];
}
if (postId) {
alertMsg = [NSString stringWithFormat:#"%#\nPost ID: %#", alertMsg, postId];
}
alertTitle = #"Success";
}
if (alertTitle) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMsg
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[self dismissActivityIndicator];
}
}
it gives me error in performPublishAction method.
can anyone tell me what is the problem . i have a lot of search and also found many solution but no one work. Please help. Thanks in advance.
I think that you have to set to FBSession what is its active session :
FBSession *session = [[FBSession alloc] init];
[FBSession setActiveSession:session];

adding a Post To Facebook Timeline from iOS APP

HI Im trying to enable a IBAction to post on an user's timeline while they have an active section. I am getting an error message stating; Implicit declaration of function "x" is invalid C99. I been reading posts about the issue but no luck and honestly I am not sure if I am doing this right at all. I updated the permissions on my fb app and got the object code from the Graph API Explorer but I dont know if Im implementing it right on my code.
Here is my post method:
-(void) aPost
{
NSMutableDictionary<FBGraphObject> *object =
[FBGraphObject openGraphObjectForPostWithType:#"website"
title:#"CR Taxi APP"
image:#"http://a4.mzstatic.com/us/r1000/047/Purple4/v4/05/cc/f2/05ccf23f-a409-1e73-a649-a5e6afc4e6eb/mzl.llffzfbp.175x175-75.jpg"
url:#"https://itunes.apple.com/cr/app/cr-taxi/id674226640?mt=8"
description:#"La nueva aplicaciĆ³n para llamar taxis!"];;
[FBRequestConnection startForPostWithGraphPath:#"{id_from_create_call}"
graphObject:object
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
// handle the result
}];
}
and this is my action method
- (IBAction)publishAction:(id)sender {
if ([FBSession.activeSession.permissions
indexOfObject:#"publish_actions"] == NSNotFound) {
NSArray *writepermissions = [[NSArray alloc] initWithObjects:
#"publish_stream",
#"publish_actions",
nil];
[[FBSession activeSession]requestNewPublishPermissions:writepermissions defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *aSession, NSError *error){
if (error) {
NSLog(#"Error on public permissions: %#", error);
}
else {
**not on the code //( error on this one) aPost(aSession, error);
}
}];
}
else {
// If permissions present, publish the story
**not on the code //(not an error on this one) aPost(FBSession.activeSession, nil);
}
}
Please help!
Thank you!
I'd guess the compiler error is actually "Implicit declaration of function 'aPost' is invalid C99", although the formatting of your action method code is wonky as written. The compiler is only going to produce that error message the first time it encounters the function call to aPost.
aPost is written as a method that has no return and takes no arguments. You are trying to call it as a C function, passing it two arguments, which the compiler interprets as an entirely new function. As aPost is written with all the hard-coded strings, you probably just want to change the calls to aPost(arg1, arg2); to [self aPost]; (provided aPost and publishAction are in the same class).
Try this: might helps you
//Write This Line in your ViewController.h File
#property (strong, nonatomic) NSMutableDictionary *postParams;
//in View Controller.m File
- (void)viewDidLoad
{
self.postParams =
[[NSMutableDictionary alloc] initWithObjectsAndKeys:
[UIImage imageNamed:#"Default.png"], #"picture",
#"Facebook SDK for iOS", #"name",
#"build apps.", #"caption",
#"testing for my app.", #"description",
nil];
[self.postParams setObject:#"hgshsghhgsls" forKey:#"message"];
}
- (IBAction)SharePressed:(id)sender {
#try {
[self openSession];
NSArray *permissions =[NSArray arrayWithObjects:#"publish_actions",#"publish_stream",#"manage_friendlists",#"read_stream", nil];
[[FBSession activeSession] reauthorizeWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
/* handle success + failure in block */
if (![session isOpen]) {
[self openSession];
}
}];
[FBRequestConnection startWithGraphPath:#"me/feed" parameters:self.postParams HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,id result,NSError *error) {
NSString *alertText;
if (error) {
alertText = [NSString stringWithFormat:#"error: domain = %#, code = %d, des = %#",error.domain, error.code,error.description];
}
else
{
alertText=#"Uploaded Successfully";
[self ResetAllcontent];
}
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Result" message:alertText delegate:self cancelButtonTitle:#"OK!"
otherButtonTitles:nil]show];
}];
}
#catch (NSException *exception) {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Please Login" message:#"For Sharing on facbook please login with facbook" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
[alert show];
}
#finally {
}
}
- (void)openSession
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
[appDelegate sessionStateChanged:session state:state error:error];
}];
ACAccountStore *accountStore;
ACAccountType *accountTypeFB;
if ((accountStore = [[ACAccountStore alloc] init]) &&
(accountTypeFB = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook] ) ){
NSArray *fbAccounts = [accountStore accountsWithAccountType:accountTypeFB];
id account;
if (fbAccounts && [fbAccounts count] > 0 &&
(account = [fbAccounts objectAtIndex:0])){
[accountStore renewCredentialsForAccount:account completion:^(ACAccountCredentialRenewResult renewResult, NSError *error) {
//we don't actually need to inspect renewResult or error.
if (error){
}
}];
}
}
}
}
//=====in your plist file do
URLTypes=>Item 0=> URL Schemes =>Item 0=>fbyourfacebookId
FacebookAppID-your facebookID
And yes dont forget to create facebook id at developer.facebook.com
and also give permissions as your need
- (IBAction)shareViaFacebook:(id)sender {
if (FBSession.activeSession.isOpen) {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:#"%#. Join on Linute.",self.userNameLabel.text], #"name",
//#"Build great social apps and get more installs.", #"caption",
locationString, #"description",
//#"http://www.linute.com/", #"link",
eventPicString, #"picture",//imageURL
nil];
// Make the request
[FBRequestConnection startWithGraphPath:#"/me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// Link posted successfully to Facebook
NSLog(#"result: %#", result);
} else {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
NSLog(#"%#", error.description);
}
}];
}else{
FBSession *session = [[FBSession alloc] initWithPermissions:#[#"public_profile", #"email",#"user_friends",#"publish_actions"]];
[FBSession setActiveSession:session];
[session openWithBehavior:FBSessionLoginBehaviorWithFallbackToWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (FBSession.activeSession.isOpen) {
[self shareViaFacebook:nil];
}else{
[self shareViaFacebook:nil];
}
}];
}

Resources