Facebook request is not sending on all devices? - ios

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

Related

Ios Facebook SDK how i can share an image,a link,a text?

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

Post multiple images using SLComposeViewController on Facebook/ Twitter?

I am an iOS developer and I am currently using SLComposeViewController to share a post on Facebook/Twitter. My issue is that I have to post multiple images in a single post.
I have done this as follows:
SLComposeViewController* mySLComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
[mySLComposerSheet setInitialText:textTobeShared];
mySLComposerSheet addURL:[NSURL URLWithString:#"http://click-labs.com/"]];
for(int count=0;count<imageArray.count;count++)
if([mySLComposerSheet addImage:[UIImage imageWithData:[imageArray objectAtIndex:count]]])
In the above code, imageArray is the array of images that I want to post.
When I am doing this on Facebook, all the images are posted as a separate post.
While in case of Twitter, addImage method returns true only for the first images while in case of other images it returns false. So only one image is posted.
So I want to know how to achieve my goal and is it possible to post multiple images in a single tweet.
I think you need to create an album first.
Here's a link to the facebook album API documentation.
- (void)shareToFacebook {
if (FBSession.activeSession.isOpen) {
NSLog(#"SESSION IS OPEN");
[self createFacebookAlbum];
} else {
NSLog(#"SESSION IS NOT OPEN");
NSArray* permissions = [NSArray arrayWithObject:#"email"];
[FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
if (error) {
/* handle failure */
NSLog(#"error:%#, %#", error, [error localizedDescription]);
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"There was a problem with your Facebook permissions." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
else if (state == FBSessionStateClosed || state == FBSessionStateClosedLoginFailed ) {
[FBSession.activeSession closeAndClearTokenInformation];
}
else if (state == FBSessionStateOpenTokenExtended || state == FBSessionStateOpen) {
if(!self.presentedFacebookSheet) {
[self performSelector:#selector(reauthorizeAndContinuePostToFacebook) withObject:nil afterDelay:0.5];
self.presentedFacebookSheet = YES;
}
}
}];
}
}
- (void)reauthorizeAndContinuePostToFacebook {
NSArray *permissions = [NSArray arrayWithObjects:#"publish_actions", nil];
[[FBSession activeSession] requestNewPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error) {
[self shareToFacebook];
}];
}
- (void)createFacebookAlbum {
NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
[parameters setObject:#"Test name" forKey:#"name"];
[parameters setObject:#"Test message" forKey:#"message"];
FBRequest* request = [FBRequest requestWithGraphPath:#"me/albums" parameters:parameters HTTPMethod:#"POST"];
NSLog(#"creating facebook album");
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
[connection addRequest:request
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString* albumId = [result objectForKey:#"id"];
NSLog(#"OK %#", albumId);
}
else {
NSLog(#"Error: %#",error.userInfo);
}
}];
[connection start];
}
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error {
switch (state) {
case FBSessionStateOpen:
{
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (error) {
//error
}
else {
NSLog(#"User session found");
}
}];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
}

Logout from facebook in iOS app

I am creating a simple iOS App that Login to facebook, Fetch self and friends details, Logout from facebook.
Now Login from Facebook and Fetching self & friends details is working ok, but I am not able to logout fully from facebook. Whenever I logout and then Login back - I see the Authorization screen instead of Authentication Login screen of Facebook (of Web).
Below is my code - can you please see if there is something wrong in the steps I have performed from Login, to Fetching self & friends details and Logging out from facebook
1) Login to Facebook using below method
- (void)openSession
{
if(FBSession.activeSession.isOpen)
{
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:NO
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error)
{
[self sessionStateChanged:session state:state error:error];
}];
}
else
{
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error)
{
[self sessionStateChanged:session state:state error:error];
}];
}
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
{
// Connection is Open
lblStatus.text = #"FBSessionStateOpen";
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
{
[FBSession.activeSession closeAndClearTokenInformation];
// Connection is Closed / Login Failed
lblStatus.text = #"FBSessionStateClosed";
}
break;
default:
break;
}
}
2) Fetching self details and Friends details using below method
if (FBSession.activeSession.isOpen)
{
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
self.lblSelfDetails.text = user.name;
self.profilePicture.profileID = user.id;
}
}];
}
FBRequest *friendRequest = [FBRequest requestForGraphPath:#"me/friends?fields=name,birthday"];
[friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
NSArray *data = [result objectForKey:#"data"];
for (FBGraphObject<FBGraphUser> *friend in data)
{
NSLog(#"%#:%#", [friend name],[friend birthday]);
}
}];
3) Logout using below method
- (IBAction)logout:(id)sender
{
[FBSession.activeSession closeAndClearTokenInformation];
}
Please use this method to logut successfully from the facebook
- (void)logout:(id<FBSessionDelegate>)delegate {
_sessionDelegate = delegate;
NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
[self requestWithMethodName:#"auth.expireSession"
andParams:params andHttpMethod:#"GET"
andDelegate:nil];
[params release];
[_accessToken release];
_accessToken = nil;
[_expirationDate release];
_expirationDate = nil;
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* facebookCookies = [cookies cookiesForURL:
[NSURL URLWithString:#"https://m.facebook.com"]];
for (NSHTTPCookie* cookie in facebookCookies) {
[cookies deleteCookie:cookie];
}
if ([self.sessionDelegate respondsToSelector:#selector(fbDidLogout)]) {
[_sessionDelegate fbDidLogout];
}
}
Hope this helps you!!!
Add this mathod in appdelegate.m
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
return [FBSession.activeSession handleOpenURL:url];
}
Then Add these methods in your .m file
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen: {
UIViewController *topViewController =
[self.navController topViewController];
if ([[topViewController modalViewController]
isKindOfClass:[SCLoginViewController class]]) {
[topViewController dismissModalViewControllerAnimated:YES];
}
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// be looking at the root view.
[self.navController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
[self showLoginView];
break;
default:
break;
}
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
- (void)openSession
{
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
Next, create a new method that will close the current session and log a person out:
-(void)logoutButtonWasPressed:(id)sender
{
[FBSession.activeSession closeAndClearTokenInformation];
}

Facebook iOS SDK 3.5 accessToken invalid

I am using the following code to login on Facebook. I am using SDK 3.5.2.
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState)state
error:(NSError *)error
{
// FBSample logic
// Any time the session is closed, we want to display the login controller (the user
// cannot use the application unless they are logged in to Facebook). When the session
// is opened successfully, hide the login controller and show the main UI.
switch (state) {
case FBSessionStateOpen: {
NSMutableDictionary *params = [[[Singleton sharedSingleton] requestParams] mutableCopy];
NSString *fbaccessToken = [session accessToken];
NSLog(#"fbaccessToken: %#", fbaccessToken);
[params setObject:fbaccessToken forKey:#"facebook_access_token"];
[params setObject:[NSString stringWithFormat:#"%d", [fbaccessToken length]] forKey:#"DEBUG_linghezza_fb_accessToken"];
[params setObject:[[FBSession activeSession] appID] forKey:#"DEBUG_appID"];
[params setObject:[[FBSession activeSession] urlSchemeSuffix] forKey:#"DEBUG_urlSchemeSuffix"];
[params setObject:[[FBSession activeSession] permissions] forKey:#"DEBUG_permessi"];
NSLog(#"%#", params);
[[[Singleton sharedSingleton] sharedClient] postPath:#"login_with_facebook.json" parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
if ([[responseObject objectForKey:#"error"] isEqualToString:#"facebook_access_token not valid"]) {
NSLog(#"closeAndClearTokenInformation");
[session closeAndClearTokenInformation];
[session close];
[FBSession setActiveSession:nil];
NSLog(#"openSessionWithAllowLoginUI");
[self openSessionWithAllowLoginUI:YES];
return;
} else {...}
...
}
- (void)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
NSLog(#"openSessionWithAllowLoginUI:allowLoginUI");
[FBSession sessionOpenWithPermissions:[[[Singleton sharedSingleton] initPrefs] objectForKey:#"facebook_permissions"] completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
[self sessionStateChanged:session state:status error:error];
}];
return;
}
When I change the password in Facebook, I cannot login any more. The server is receiving
{
error: {
message: "Error validating access token: The session has been invalidated because the user has changed the password.",
type: "OAuthException",
code: 190,
error_subcode: 460
}
}
Everytime I try to refresh the token, I continue to receive the old token that the server cannot validate.
The server validates it with the following OpenGraph URI:
https://graph.facebook.com/me?access_token=ACCESS_TOKEN
How shall I fix this? Thank you

Dismiss facebook window programmatically

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

Resources