My requirement is to close Facebook window in certain conditions via code.
I am using Facebook iOS SDK 3.5.1.
Is there any way to get visible (Facebook) screen on running app or to dismiss Facebook screen programmatically?
I am using facebook for 2 scenarios-
for login
for sending app request.
Code for both are below-
1. For login:
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
if (appDelegate.session.state != FBSessionStateCreated || !appDelegate.session.isOpen) {
// Create a new, logged out session.
NSArray *permissions = [NSArray arrayWithObjects:#"publish_stream",#"user_birthday",#"user_photos", #"email", #"user_location", #"user_hometown", nil];
appDelegate.session = [[FBSession alloc] initWithPermissions:permissions];
}
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if (appDelegate.session.state!=258 && appDelegate.session.state!=257) {
[self accessTokenFound:appDelegate.session.accessToken];
}
}];
2. For app requests
NSMutableDictionary* params = [NSMutableDictionary dictionary];
AppDelegate* appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
[params setObject:friendID forKey:#"to"];
// Display the requests dialog
[FBWebDialogs
presentRequestsDialogModallyWithSession:appDelegate.session
message:message
title:nil
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
NSLog(#"Error sending request.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
NSLog(#"User canceled request.");
} else {
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"request"]) {
NSLog(#"User canceled request.");
} else {
NSString *requestID = [urlParams valueForKey:#"request"];
[self requestSentSuccessfully];
}
}
}
}];
Related
I'm using the last facebook sdk in my ios app and i'm trying to share an image with a description and a link. I have tried
[FBDialogs presentShareDialogWithLink]
but i can't see my description text in the shared result. I have tried
[FBDialogs presentShareDialogWithPhotoParams]
but the description field of the FBPhotoParams is "onlyread" and i can't add any text. So i have abandoned the various fbdialogs and i have tried something that works in another my app:
if ([[FBSession activeSession] isOpen]) {
/*
* if the current session has no publish permission we need to reauthorize
*/
if ([[[FBSession activeSession] permissions]indexOfObject:#"publish_actions"] == NSNotFound) {
[[FBSession activeSession] requestNewPublishPermissions:[NSArray arrayWithObject:#"publish_actions"] defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session,NSError *error){
[self share];
}];
}else{
[self share];
}
}else{
/*
* open a new session with publish permission
*/
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceOnlyMe
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (!error && status == FBSessionStateOpen) {
[self share];
}else{
NSLog(#"error");
}
}];
}
Now this method not working and return me an error:
"OAuth \"Facebook Platform\" \"insufficient_scope\" \"(#200) The user hasn't authorized the application to perform this action\"";
I haven't the permission to share, but the user never see the permission dialog...Maybe i have to submit my application to Facebook for achive a "general" ublish_actions permission for my facebook app? It's only a link, i don't wanna send a build, wait an approvation,ecc.. Now it's really so complicated to share a link with an image and a text? There will be a simpler solution , i think... How i can do?
use this,
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);
}
}
}
}];
- (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 am trying to follow the Parse tutorial for Logging in With Facebook. However, the sample code does not match up with the guide, so the code there is useless. I have followed the guide completely, but after I login, it directs me to Facebook app, I give permission, it goes back to the app I am building, but I get the following error
FBSDKLog: Error for request to endpoint 'me': An open FBSession must be specified for calls to this endpoint.
What is going on? In Login controller:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// handle successful response
} else if ([[[[error userInfo] objectForKey:#"error"] objectForKey:#"type"]
isEqualToString: #"OAuthException"]) { // Since the request failed, we can check if it was due to an invalid session
NSLog(#"The facebook session was invalidated");
[self logoutButtonAction:nil];
} else {
NSLog(#"Some other error: %#", error);
}
}];
if ([PFUser currentUser] && // Check if user is cached
[PFFacebookUtils isLinkedWithUser:[PFUser currentUser]]) { // Check if user is linked to Facebook
// Present the next view controller without animation
[self _presentUserDetailsViewControllerAnimated:NO];
}
}
- (IBAction)loginButtonTouchHandler:(id)sender {
// Set permissions required from the facebook user account
NSArray *permissionsArray = #[ #"user_about_me", #"user_relationships", #"user_birthday", #"user_location"];
[PFFacebookUtils initializeFacebook];
// Login PFUser using Facebook
[PFFacebookUtils logInWithPermissions:permissionsArray block:^(PFUser *user, NSError *error) {
[_activityIndicator stopAnimating]; // Hide loading indicator
if (!user) {
NSString *errorMessage = nil;
if (!error) {
NSLog(#"Uh oh. The user cancelled the Facebook login.");
errorMessage = #"Uh oh. The user cancelled the Facebook login.";
} else {
NSLog(#"Uh oh. An error occurred: %#", error);
errorMessage = [error localizedDescription];
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Log In Error"
message:errorMessage
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:#"Dismiss", nil];
[alert show];
} else {
if (user.isNew) {
NSLog(#"User with facebook signed up and logged in!");
} else {
NSLog(#"User with facebook logged in!");
}
[self _presentUserDetailsViewControllerAnimated:YES];
}
}];
[_activityIndicator startAnimating]; // Show loading indicator until login is finished
}
- (void)_presentUserDetailsViewControllerAnimated:(BOOL)animated {
UserDetailsViewController *detailsViewController = [[UserDetailsViewController alloc] init];
[self.navigationController pushViewController:detailsViewController animated:YES];
}
In my UserDetailsViewController:
- (void)viewDidLoad {
// ...
[self _loadData];
}
- (void)_loadData {
// ...
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// result is a dictionary with the user's Facebook data
NSDictionary *userData = (NSDictionary *)result;
NSString *facebookID = userData[#"id"];
NSString *name = userData[#"name"];
NSString *location = userData[#"location"][#"name"];
NSString *gender = userData[#"gender"];
NSString *birthday = userData[#"birthday"];
NSString *relationship = userData[#"relationship_status"];
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookID]];
// URL should point to https://graph.facebook.com/{facebookId}/picture?type=large&return_ssl_resources=1
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:pictureURL];
// Run network request asynchronously
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[NSOperationQueue mainQueue]
completionHandler:
^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError == nil && data != nil) {
// Set the image in the header imageView
self.headerImageView.image = [UIImage imageWithData:data];
}
}];
// Now add the data to the UI elements
// ...
}
}];
}
We figured it out, when trying to create an auto-login feature with this function:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// handle successful response
} else if ([[[[error userInfo] objectForKey:#"error"] objectForKey:#"type"]
isEqualToString: #"OAuthException"]) { // Since the request failed, we can check if it was due to an invalid session
NSLog(#"The facebook session was invalidated");
[self logoutButtonAction:nil];
} else {
NSLog(#"Some other error: %#", error);
}
}];
if ([PFUser currentUser] && // Check if user is cached
[PFFacebookUtils isLinkedWithUser:[PFUser currentUser]]) { // Check if user is linked to Facebook
// Present the next view controller without animation
[self _presentUserDetailsViewControllerAnimated:NO];
}
}
We actually end up skipping the [PFFacebookUtils initializeFacebook] call, since it only happens when you push the login button. The solution is to put this call in the appDelegate in the method application:didFinishLaunchingWithOptions:
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];
}
}];
}
I wrote code
- (void)sendRequest {
NSLog(#"SEND REQUEST ");
// Display the requests dialog
[FBWebDialogs
presentRequestsDialogModallyWithSession:nil
message:#"www.demoapp.com"
title:nil
parameters:nil
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Error launching the dialog or sending the request.
NSLog(#"Error sending request.");
[FBSession.activeSession closeAndClearTokenInformation];
[FBSession.activeSession close];
[FBSession setActiveSession:nil];
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// User clicked the "x" icon
NSLog(#"User canceled request.");
[FBSession.activeSession closeAndClearTokenInformation];
[FBSession.activeSession close];
[FBSession setActiveSession:nil];
} else {
// Handle the send request callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"request"]) {
// User clicked the Cancel button
NSLog(#"User canceled request.");
[FBSession.activeSession closeAndClearTokenInformation];
[FBSession.activeSession close];
[FBSession setActiveSession:nil];
} else {
// User clicked the Send button
NSString *requestID = [urlParams valueForKey:#"request"];
NSLog(#"Request ID: %#", requestID);
[FBSession.activeSession closeAndClearTokenInformation];
[FBSession.activeSession close];
[FBSession setActiveSession:nil];
}
}
}
}];
}
- (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;
}
and calling it like
- (void)sendRequestButtonAction {
NSLog(#"sendRequestButtonAction");
AppDelegate *appDelegate =
(AppDelegate *) [[UIApplication sharedApplication] delegate];
if (FBSession.activeSession.isOpen) {
[appDelegate sendRequest];
}
}
I am sending from iPhone simulator and receiving in iPhone device and Android Device, but I am unable to receive in iPad,
I am amazed and cannot find solution at my end.
Please help
I am using FacebookSDK in one of my applications to Login to the app and Share something. The login is completed and i can now Login to the application using this SDK. Below is the code I am using for login.
-(void)didSelectLoginWithFB
{
if (FBSession.activeSession.isOpen) {
[appDelegate closeSession];
}
else {
[appDelegate openSessionWithAllowLoginUI:YES];
}
if(FBSession.activeSession.accessToken ){
[self performSelector:#selector(FBLoginAction) withObject:nil];
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(FBLoginDidFinish:)
name:#"FBLoginDidFinish"
object:appDelegate];
}
-(void)FBLoginDidFinish:(NSNotification *)notification
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self performSelector:#selector(FBLoginAction) withObject:nil];
}
-(void)FBLoginAction
{
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
NSDictionary *userInfo = (NSDictionary *)user;
NSLog(#"User dic %#",userInfo);
// fbUserId = user.id;
// NSLog(#"User dic %#",fbUserId);
userMail = [userInfo objectForKey:#"email"];
NSLog(#"User E Mail --- %#", userMail);
loginFlag = 200;
[self getDataFromServer:nil];
}
else{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Facebook Connection Error !!" message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil ];
[alert show];
}
}];
}
}
Now, I want to post something to the User's facebook wall (timeline). How can I do this using this SDK ? I didn't get any info from developer.facebook.com for this sdk.
Please Help !
I know this is very late, but I hope it'll help..
You can use following code to post on user's wall/timeline-
- (void)postToFacebook{
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
if (appDelegate.session.state != FBSessionStateCreated || !appDelegate.session.isOpen){
// Create a new, logged out session.
NSArray *permissions = [NSArray arrayWithObject:#"publish_actions, publish_stream"];
appDelegate.session = [[FBSession alloc] initWithPermissions:permissions];
// if the session isn't open, let's open it now and present the login UX to the user
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if (appDelegate.session.state!=258 && appDelegate.session.state!=257) {
[self postOpenGraphAction];
}
}];
}else{
if (appDelegate.session.isOpen) {
[self postOpenGraphAction];
}
}
}
- (void)postOpenGraphAction {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys: #"", #"picture", #"", #"name", #"", #"link", #"", #"caption", #"", #"description", #"Your message to post", #"message", nil];
AppDelegate *appDelegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
[FBSession setActiveSession:appDelegate.session];
[FBRequestConnection startWithGraphPath:#"me/feed" parameters:params HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (error) {
NSLog(#"Error on publishing story: %#", error);
} else {
NSLog(#"Published on wall successfully");
}
}];
}
I have used session object created in my AppDelegate, instead of FBSession activeSession.
You can use as per your code.