Unable to implement a custom Facebook login button for IOS - facebook

I am trying to create a custom login button for IOS 9,i have been following the Facebook's tutorial for doing so but when i button is clicked,i end up getting this error
libc++abi.dylib: terminate_handler unexpectedly threw an exception
I have been following this Facebook tutorial,only difference is i am using dispatch_async due to some reasons.
https://developers.facebook.com/docs/facebook-login/ios#loginkit
dispatch_async(dispatch_get_main_queue(), ^{
NSMutableArray* Permissions = [[NSMutableArray alloc] init];
[Permissions addObject:#"email"];
[Permissions addObject:#"public_profile"];
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logInWithReadPermissions:Permissions
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error)
{
NSLog(#"Process error");
}
else if (result.isCancelled)
{
NSLog(#"Cancelled");
}
else
{
NSLog(#"Logged in");
}
];
});
I have tried using Parse SDK's code too like so...
NSArray *permissionsArray = #[ #"user_about_me", #"user_relationships", #"user_birthday", #"user_location"];
[PFFacebookUtils logInInBackgroundWithReadPermissions:permissionsArray block:^(PFUser *user, NSError *error)
{
if (!user)
{
NSLog(#"Uh oh. The user cancelled the Facebook login.");
}
else if (user.isNew)
{
NSLog(#"User signed up and logged in through Facebook!");
}
else
{
NSLog(#"User logged in through Facebook!");
}
}];
But both the time,i end up getting the same error like as shown in the image below..
Error message image
Am i doing something wrong in app validation process?
Please help!
Thank you!

This is weird,after playing around in Xcode,i found that it is not able to get my appID and other settings from my plist even though it's there.After i programmatically set my app id using
[FBSDKSettings setAppID:#"appid"];
[FBSDKSettings setDisplayName:#"displayname"];
I was to able get rid of that error,but i am stuck at URLSchemes...i will recreate the project and try again!
Thank you!
It's working now and,i am able to get a login page,but after i get past the app login screen,i am getting a blank white screen with only a done button at th top right corner,when i click it,i get the log message that the user cancelled login.

Related

Always return Error FBErrorCategoryUserCancelled while login with facebook in my application

In my Application there are three ways of login. one of them is login with facebook. But when I click on facebook button it ask me for accesing permissions, when click OK then it returs error FBErrorCategoryUserCancelled. And this is not happening on every devices, it happens on some devices. Here is my code -
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){
[ProgressHUD dismiss];
self.view.userInteractionEnabled = YES;
}];
}else{
[self fetchUserDetails];
}
}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 fetchUserDetails];
}else{
NSLog(#"error");
if ([FBErrorUtility shouldNotifyUserForError:error]) {
alertTitle = #"Facebook Error";
alertMessage = [FBErrorUtility userMessageForError:error];
// This code will handle session closures that happen outside of the app
// You can take a look at our error handling guide to know more about it
// https://developers.facebook.com/docs/ios/errors
} else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryAuthenticationReopenSession) {
alertTitle = #"Session Error";
alertMessage = #"Your current session is no longer valid. Please log in again.";
// If the user has cancelled a login, we will do nothing.
// You can also choose to show the user a message if cancelling login will result in
// the user not being able to complete a task they had initiated in your app
// (like accessing FB-stored information or posting to Facebook)
} else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryUserCancelled) {
NSLog(#"user cancelled login");
alertTitle = #"Facebook Error";
alertMessage = #"System login cancelled";
// For simplicity, this sample handles other errors with a generic message
// You can checkout our error handling guide for more detailed information
// https://developers.facebook.com/docs/ios/errors
} else {
alertTitle = #"Something went wrong";
alertMessage = #"Please try again later.";
NSLog(#"Unexpected error:%#", error);
}
[[[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
[ProgressHUD dismiss];
self.view.userInteractionEnabled = YES;
}
}];
}
Any help will be appreciated.Thank you.
In my case it was because the facebook app's sandbox mode was still on, and therefore result in FBErrorCategoryUserCancelled for anyone who is not an administrator/developer/tester of the app.
To turn off sandbox mode on facebook, go to
https://developers.facebook.com/apps/YOUR_FACEBOOK_APP_ID/review-status/
See where it says "Do you want to make this app and all its live features available to the general public?", make it to be YES. (You might need to insert a contact email before you can access this option).
Or, if you don't want to make the app go public just yet, invite the tester to be an admin/developer/tester of the app. The person need to accept your invitation before he can use it.

Fb request dialog returns nil incorrectly - IOS Facebook

Thanks for reading!
I'm trying to create a Facebook request to enable the user to invite his friends to the app.
NSDictionary *params = [[NSDictionary alloc] initWithObjectsAndKeys:nil];
[FBWebDialogs
presentRequestsDialogModallyWithSession:nil
message:#"Learn how to make your iOS apps social."
title:#"Test"
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Error launching the dialog or sending the request.
NSLog(#"Error sending request.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// User clicked the "x" icon
NSLog(#"User canceled request.");
} 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.");
} else {
// User clicked the Send button
NSString *requestID = [urlParams valueForKey:#"request"];
NSLog(#"Request ID: %#", requestID);
}
}
}
}];
}
This is pretty much a clean copy of the Facebook docs code. And it works up to a point
The user can choose the friends and the request goes away and gets received by the friends and it shows up as a notification - everything fine so far.
The problem is that when I try to get the response from the "handler" the resultURL is nil and does not contain anything. And after that I get the log message "User canceled request".
Why don't I get anything back? The main reason that I need this is that I need to know which friends the request was sent to.
Thank you for any help!
Seems like you're passing an nil empty session to presentRequestsDialogModallyWithSession
Use FBSession.activeSession instead and check you have enough permissions to run the request (although if not, you would be getting another different error)
I think you are not having a session opened..please try to use this to open the session.
if (!FBSession.activeSession.isOpen) {
// 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) {
}];
}

Facebook SDK 3.1 error when posting from iOS app

I'm facing the following problems with my iOS app:
While publishing to user's friend's wall, using iOS app I'm getting the error "com.facebook.sdk error 5".
The app is asking to login every time when I check for "FBSession.activeSession.isOpen".
Everything was working fine before. But since I've changed my app ID (as now I have to use different Facebook app). I'm getting the error.
I've done some research on this and found some solutions. Ive tried them all but nothing works.
I've written the following code to login to Facebook:
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
comingfromFB = YES;
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"friends_birthday",
nil];
return [FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
And the following code for publishing story:
if ([FBSession.activeSession.permissions
indexOfObject:#"publish_actions"] == NSNotFound) {
// No permissions found in session, ask for it
[FBSession.activeSession
reauthorizeWithPublishPermissions:
[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
// If permissions granted, publish the story
[self publishStory];
}
}];
} else {
// If permissions present, publish the story
[self publishStory];
}
When I run the app I get the following error:
Error: HTTP status code: 403
2013-02-05 14:36:47.109 <appname>[1705:c07] Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0xaa9af20 {com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 200;
message = "(#200) The user hasn't authorized the application to perform this action";
type = OAuthException;
};
};
code = 403;
}, com.facebook.sdk:HTTPStatusCode=403}
Please help me to understand where I'm going wrong.
I've also added some key-value pair to NSUserDefaults. Could that be a possible reason for that?
Thanks.
When you're first showing your view with post button, perhaps you want to check if the session is open and set your post button title according to session state. Assuming your button initially has "Post" title:
[FBSession openActiveSessionWithAllowLoginUI: NO];
if (![FBSession.activeSession isOpen])
{
[self setSendButtonTitle:NSLocalizedString(#"Log in",#"")];
}
Then add the following code to your Post button action:
- (void) send: (UIButton*) sender
{
if (![FBSession.activeSession isOpen])
{
[FBSession openActiveSessionWithPublishPermissions: [NSArray arrayWithObjects: #"publish_stream", nil]
defaultAudience: FBSessionDefaultAudienceEveryone
allowLoginUI: YES
completionHandler: ^(FBSession *session,
FBSessionState status,
NSError *error)
{
if (error)
{
NSLog(#"error");
}
else
{
[FBSession setActiveSession:session];
[self setSendButtonTitle: NSLocalizedString(#"Post",#"")];
}
}];
return;
}
// here comes the code you use for sending the message
}
So if the user presses send and the app is not authorized, it will perform a login operation and change your Post button title from "Log in" to "Post". Then the user will be able to post the message by pressing the button once again.
Hope it helps

Facebook Login ask to install (iPhone)

I need help in the facebook login from Facebook-SDK-3.1 for iOS 6.I have used all the code of the Facebook sdksample code sessionLoginSample,I have used the WebView opening code in this and whenever i login from the new id ...it takes me to the below image link to install in my project .dont know what exactly it is...and if i do so and after that logout from the code ..and when I again press button to login , it automatically log-in without asking for the id and pssword``login page. and again again it automatically logs-in , even after logout./.can anyone help me why after being logout it ask stores the previous access token and password.
and code is
- (IBAction)buttonClickHandler:(id)sender {
AppDelegate* appDelegate = [[UIApplication sharedApplication]delegate];
if (appDelegate.session.isOpen) {
[appDelegate.session closeAndClearTokenInformation];
} else {
if (appDelegate.session.state != FBSessionStateCreated) {
appDelegate.session = [[FBSession alloc] initWithPermissions:[NSArray arrayWithObjects:#"email", nil]];
}
[appDelegate.session openWithBehavior:FBSessionLoginBehaviorForcingWebView
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
FBSession.activeSession = session;
[self updateView];
NSLog(#" state=%d",state);
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error) {
userInfo = #"";
userInfo = user.username;
NSLog(#"string %#", userInfo);
[self checkfacebook];
}];
}]; }
}
FB grants access to your app once the user logs in . If the user wants to modify the privileges he can do it by loggin into fb and changing permissions. You might want to look into oAuth for further details.
As u login through new emailid it has to install your app for them...so,its asking for different login..but again u login with the same it will not ask...the answer for ur 2nd question is....is u doing something to the server side...bcoz there might be a provision on the server which remember user for few hour or few days...so,check with server side..if not working with server...reply me back i will try to answer further...

i want to store some data in "EverNote" through our app

i want to store some data in "EverNote" through our app either (image or text or both).
I googled, i got some guidance like EverNote SDK and i got the EverNoteCounter Sample also(When i run this, when i click getCount button it shows an alert message "Could not authenticate").
I generated the developer token also.
But i unable to create the consumerKey,consumerSecret. And also i did not find how to store our data to evernote from our app.
I got some links like this one
but when i go through that link it says( HTTP method GET is not supported by this URL)
I able to authenticate with the EVERNOTE and i able to get the number of notebooks in that Account.
I am using sqllite in my app. i am using one folder for images. Sqllite have the images links info.
How to store the data.
I used the following code to authenticate and to get the count
- (IBAction)retrieveUserNameAndNoteCount:(id)sender
{
// Create local reference to shared session singleton
EvernoteSession *session = [EvernoteSession sharedSession];
[session authenticateWithViewController:self completionHandler:^(NSError *error) {
// Authentication response is handled in this block
if (error || !session.isAuthenticated) {
// Either we couldn't authenticate or something else went wrong - inform the user
if (error) {
NSLog(#"Error authenticating with Evernote service: %#", error);
}
if (!session.isAuthenticated) {
NSLog(#"User could not be authenticated.");
}
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Error"
message:#"Could not authenticate"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] autorelease];
[alert show];
} else {
// We're authenticated!
EvernoteUserStore *userStore = [EvernoteUserStore userStore];
// Retrieve the authenticated user as an EDAMUser instance
[userStore getUserWithSuccess:^(EDAMUser *user) {
// Set usernameField (UILabel) text value to username
[usernameField setText:[user username]];
// Retrieve total note count and display it
[self countAllNotesAndSetTextField];
} failure:^(NSError *error) {
NSLog(#"Error retrieving authenticated user: %#", error);
}];
}
}];
}
- (void)countAllNotesAndSetTextField
{
// Allow access to this variable within the block context below (using __block keyword)
__block int noteCount = 0;
EvernoteNoteStore *noteStore = [EvernoteNoteStore noteStore];
[noteStore listNotebooksWithSuccess:^(NSArray *notebooks) {
for (EDAMNotebook *notebook in notebooks) {
if ([notebook guid]) {
EDAMNoteFilter *filter = [[EDAMNoteFilter alloc] init];
[filter setNotebookGuid:[notebook guid]];
[noteStore findNoteCountsWithFilter:filter withTrash:NO success:^(EDAMNoteCollectionCounts *counts) {
if (counts) {
// Get note count for the current notebook and add it to the displayed total
NSNumber *notebookCount = (NSNumber *)[[counts notebookCounts] objectForKey:[notebook guid]];
noteCount = noteCount + [notebookCount intValue];
NSString *noteCountString = [NSString stringWithFormat:#"%d", noteCount];
[noteCountField setText:noteCountString];
}
} failure:^(NSError *error) {
NSLog(#"Error while retrieving note counts: %#", error);
}];
}
}
} failure:^(NSError *error) {
NSLog(#"Error while retrieving notebooks: %#", error);
}];
}
Please suggest me the links or give me the guidance
Thanks a lot in advance
Developer token is to be used when you only need to access your own account. To get a consumer key/secret, go here : http://dev.evernote.com/documentation/cloud/ .
If you are using iOS, https://github.com/evernote/evernote-sdk-ios has a sample app that you can use once you have a consumer key and secret.
In general, there is a lot of information on dev.evernote.com.
All SDKs are located at https://github.com/evernote
Getting started guide for iOS : http://blog.evernote.com/tech/2012/05/24/evernote-sdk-integration-ios/
Did you solved it? If not, i did the following to get it work:
download and include sdk
get consumerKey and secret (if you want to access notes too, then
instead of basic you should request for full access, http://dev.evernote.com/documentation/cloud/ top right corner)
Add the URLType entry in info.plist ("Modify your application's main
plist file" chapter https://github.com/evernote/evernote-sdk-ios)
Copy the session init code (filled with consumer key and secret, the hostname should be left unchanged) and implement the two application delegate specific code
An (on-screen) viewcontroller should be passed on authenticating the user to authenticateWithViewController method, f.e. the appdelegate's rootViewController
Study this pages to understand the model hierarchy used by Evernote:
http://dev.evernote.com/documentation/cloud/chapters/data_structure.php
http://dev.evernote.com/documentation/reference/Types.html
Image could be stored as EDAMResource (Resource) in the field data and text as EDAMNote (Note) in the field content. Both is handled by Evernote SDK's EvernoteNoteStore object.