I'm developing an app for FB wall posting in ios using facebook sdk 3.5. I'm using two views. Firts one is a splash screen and a second one is the facebook login view. When i'm activate both views I'm getting a thread and error displayed,
2013-05-17 17:07:59.115 [415:12503] * Assertion failure in -[FBSession checkThreadAffinity], /Users/chrisp/tmp/sdk/ios-sdk/src/FBSession.m:1571
2013-05-17 17:07:59.127 [415:12503] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'FBSession: should only be used from a single thread'
* First throw call stack:
(0x2387052 0x1fa3d0a 0x232fa78 0x1a9c2db 0x21fa2 0x1e626 0x1ecd9 0x22b67 0x1eba3 0x3c265 0x2388ec9 0x11165c2 0x111655a 0x11bbb76 0x11bc03f 0x11bb2fe 0x113ba30 0x113bc56 0x1122384 0x1115aa9 0x293ffa9 0x235b1c5 0x22c0022 0x22be90a 0x22bddb4 0x22bdccb 0x293e879 0x293e93e 0x1113a9b 0x2be2 0x2b15)
terminate called throwing an exception(lldb)
Here is my Appdelegate.m code,
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]autorelease];
// Override point for customization after application launch.
self.viewController = [[[SplashViewController alloc] initWithNibName:#"SplashViewController" bundle:nil]autorelease] ;
// self.loginViewController = [[secondview alloc] initWithNibName:#"secondview"
// bundle:nil];
// self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.loginViewController];
// self.navigationController.delegate = self;
// self.window.rootViewController = self.navigationController;
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
//
//
UIBackgroundTaskIdentifier backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^{NSLog(#"BackgroundTask Expiration Handler is called");
[application endBackgroundTask:backgroundTask];
}];
And this is the facebook_view.m code
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.navigationController.navigationBarHidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
self.navigationController.navigationBarHidden = NO;
}
- (void)viewDidUnload {
[self setFBLoginView:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - FBLoginView delegate
- (void)loginViewShowingLoggedInUser:(FBLoginView *)loginView {
// Upon login, transition to the main UI by pushing it onto the navigation stack.
TNLRadioAppDelegate *appDelegate = (TNLRadioAppDelegate *)[UIApplication sharedApplication].delegate;
[self.navigationController pushViewController:((UIViewController *)appDelegate.viewController) animated:YES];
}
- (void)loginView:(FBLoginView *)loginView
handleError:(NSError *)error{
NSString *alertMessage = nil, *alertTitle;
// Facebook SDK * error handling *
// Error handling is an important part of providing a good user experience.
// Since this sample uses the FBLoginView, this delegate will respond to
// login failures, or other failures that have closed the session (such
// as a token becoming invalid). Please see the [- postOpenGraphAction:]
// and [- requestPermissionAndPost] on `SCViewController` for further
// error handling on other operations.
if (error.fberrorShouldNotifyUser) {
// If the SDK has a message for the user, surface it. This conveniently
// handles cases like password change or iOS6 app slider state.
alertTitle = #"Something Went Wrong";
alertMessage = error.fberrorUserMessage;
} else if (error.fberrorCategory == FBErrorCategoryAuthenticationReopenSession) {
// It is important to handle session closures as mentioned. You can inspect
// the error for more context but this sample generically notifies the user.
alertTitle = #"Session Error";
alertMessage = #"Your current session is no longer valid. Please log in again.";
} else if (error.fberrorCategory ==
FBErrorCategoryUserCancelled) {
// The user has cancelled a login. You can inspect the error
// for more context. For this sample, we will simply ignore it.
NSLog(#"user cancelled login");
} else {
// For simplicity, this sample treats other errors blindly, but you should
// refer to https://developers.facebook.com/docs/technical-guides/iossdk/errors/ for more information.
alertTitle = #"Unknown Error";
alertMessage = #"Error. Please try again later.";
NSLog(#"Unexpected error:%#", error);
}
if (alertMessage) {
[[[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
}
}
- (void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView {
// Facebook SDK * login flow *
// It is important to always handle session closure because it can happen
// externally; for example, if the current session's access token becomes
// invalid. For this sample, we simply pop back to the landing page.
TNLRadioAppDelegate *appDelegate = (TNLRadioAppDelegate *)[UIApplication sharedApplication].delegate;
if (appDelegate.isNavigating) {
// The delay is for the edge case where a session is immediately closed after
// logging in and our navigation controller is still animating a push.
[self performSelector:#selector(logOut) withObject:nil afterDelay:.5];
} else {
[self logOut];
}
}
- (void)logOut {
[self.navigationController popToRootViewControllerAnimated:YES];
}
Cqan any one help???
It sounds like you're accessing your FBSession instance from more than one thread. Check that you're not calling [FBSession activeSession] or anything similar from a background thread (or that you're always calling it from the same background thread).
Related
I have a 'Terms and Conditions' controller I represent in the first launch of the app, but when opening the app in the first time from the App Store page the Terms and Conditions' controller not shown- only after I close the app and reopen it from the device itself (not the App Store page) then the controller is shown.
this code is from the launched screen controller:
- (void)viewDidLoad {
[self agreedToServerTerms];
}
- (void)agreedToServerTerms {
[[HttpUtils instance] httpRequest:TERMS_AGREEMENT_URL :params completionHandler:^(NSData *data, NSError *error) {
#try {
bool acceptTerms = false;
if (error) {
[Utils log:[NSString stringWithFormat:#"agreedToServerTerms error=%#", error]];
} else {
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (!error) {
acceptTerms = [jsonData.allValues[0] boolValue];
if (!acceptTerms) {
TermsAndConditionController *tac = [[TermsAndConditionController alloc] initWithNibName:#"TermsAndConditionController" bundle:nil];
tac.delegate = self;
[[SlideNavigationController sharedInstance] pushViewController:tac animated:false];
}
else {
[self performSelectorInBackground:#selector(initialApp) withObject:nil];
}
} else {
[Utils log:[NSString stringWithFormat:#"parsing jsonData error = %#" ,error]];
}
}
} #catch (NSException *e) {
[Utils log:[NSString stringWithFormat:#"Exception occurred: %#, %#", e, [e userInfo]]];
}
}];
}
from App delegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
LaunchScreenController *bbp = [[LaunchScreenController alloc] initWithNibName:#"LaunchScreenController" bundle:nil];
[[SlideNavigationController sharedInstance] pushViewController:bbp animated:YES];
if (_launchedURL) {
bbp.launchedURL = _launchedURL;
}
[self.window addSubview:bbp.view];
}
herewith how I do almost the exact same thing. I think you need to rework yours, it could be a bit different, but this may help.
In the first VC that my app displays, in its viewWillAppear message, I have the following code
// Terms of use
if ( [NSUserDefaults.standardUserDefaults integerForKey:#"tou"] != 20170614 )
{
[self performSegueWithIdentifier:#"tou" sender:nil];
[NSUserDefaults.standardUserDefaults setInteger:20170614 forKey:#"tou"];
}
This uses user defaults to note if the terms of use have ever been presented and, if so, it marks #"tou" with some arbitrary value. In your case you can set the logic in your controller and only mark it once the user accepts.
This requires a segue in the storyboard called #"tou" that will present your T&C controller and you may need to prevent exit if the user does not agree, but the idea is to segue away from your first VC if the user did not agree yet to present the user with the T&C rather than injecting it into the app delegate as you do at present.
In my main view controller, when a button is pressed I run the following code:
if (![PFUser currentUser]) { // No user logged in
// Create the log in view controller
CustomSignUp *logInViewController = [[CustomSignUp alloc] init];
[logInViewController setDelegate:self]; // Set ourselves as the delegate
// Create the sign up view controller
self.signUpViewController = [[TheActualSignUp alloc] init];
[self.signUpViewController setDelegate:self]; // Set ourselves as the delegate
self.signUpViewController.fields = (PFSignUpFieldsUsernameAndPassword
| PFSignUpFieldsSignUpButton
| PFSignUpFieldsEmail
| PFSignUpFieldsAdditional
| PFSignUpFieldsDismissButton);
[self.signUpViewController.signUpView.additionalField setPlaceholder:#"First & Last Name"];
[logInViewController setSignUpController:self.signUpViewController];
logInViewController.facebookPermissions = #[ #"email", #"public_profile", #"user_friends" ];
logInViewController.fields = (PFLogInFieldsUsernameAndPassword
| PFLogInFieldsFacebook
| PFLogInFieldsTwitter
| PFLogInFieldsLogInButton
| PFLogInFieldsSignUpButton
| PFLogInFieldsPasswordForgotten);
// Present the log in view controller
[self.navigationController pushViewController:logInViewController animated:YES];
}
The view controller for a login screen shows up, and I can successfully log in an already created user. However, when I try to sign up someone, I run into issues. The sign up window appears fine, and I type in all the codes, but when I click the button to send the info in to sign it up, nothing happens. Here is the code (in the same view controller). Would greatly appreciate any help on this. Am using Parse on Buddy.com. None of the NSLogs are getting called when signing up.
- (BOOL)logInViewController:(PFLogInViewController *)logInController shouldBeginLogInWithUsername:(NSString *)username password:(NSString *)password {
// Check if both fields are completed
if (username && password && username.length != 0 && password.length != 0) {
return YES; // Begin login process
}
[[[UIAlertView alloc] initWithTitle:#"Missing Information"
message:#"Make sure you fill out all of the information!"
delegate:nil
cancelButtonTitle:#"ok"
otherButtonTitles:nil] show];
return NO; // Interrupt login process
}
// Sent to the delegate when a PFUser is logged in.
- (void)logInViewController:(PFLogInViewController *)logInController didLogInUser:(PFUser *)user {
PFUser *me = [PFUser currentUser];
NSLog(#"Regular Login");
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)logInViewController:(PFLogInViewController *)logInController didFailToLogInWithError:(NSError *)error {
NSLog(#"Failed to log in...%#", error);
}
// Sent to the delegate when the log in screen is dismissed.
- (void)logInViewControllerDidCancelLogIn:(PFLogInViewController *)logInController {
[self.navigationController popViewControllerAnimated:YES];
}
- (BOOL)signUpViewController:(PFSignUpViewController *)signUpController shouldBeginSignUp:(NSDictionary *)info {
NSLog(#"Signup");
BOOL informationComplete = YES;
// loop through all of the submitted data
for (id key in info) {
NSString *field = [info objectForKey:key];
if (!field || field.length == 0 || ![signUpController.signUpView.additionalField.text containsString:#" "] ) { // check completion
informationComplete = NO;
break;
}
}
// Display an alert if a field wasn't completed
if (!informationComplete) {
[[[UIAlertView alloc] initWithTitle:#"Missing Information"
message:#"Make sure you fill out all of the information, including first & last name!"
delegate:nil
cancelButtonTitle:#"ok"
otherButtonTitles:nil] show];
}
return informationComplete;
}
- (void)signUpViewController:(PFSignUpViewController *)signUpController didSignUpUser:(PFUser *)user {
NSLog(#"Signed them up");
[user saveEventually];
[self dismissViewControllerAnimated:YES completion:nil]; // Dismiss the PFSignUpViewController
}
// Sent to the delegate when the sign up attempt fails.
- (void)signUpViewController:(PFSignUpViewController *)signUpController didFailToSignUpWithError:(NSError *)error {
NSLog(#"Failed to sign up...");
}
// Sent to the delegate when the sign up screen is dismissed.
- (void)signUpViewControllerDidCancelSignUp:(PFSignUpViewController *)signUpController {
NSLog(#"User dismissed the signUpViewController");
}
Looking through your code, it's not immediately obvious as to what the problem is. If you ping Parse on Buddy's customer support at support#buddy.com, we can help.
I am using Xcode 6 beta with iOS 8 on the iPhone 5s the iphone 4s is standard ios 7.1 phone.
The app runs great on the iPhone 5s but as soon as a try a iphone 4s or the iPhone 4s simulator.
the app breaks out and throws the following error
dyld: Symbol not found: _NSURLAuthenticationMethodClientCertificate
Referenced from: /Users/MIkeAspinall 1/Library/Developer/CoreSimulator/Devices/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx/data/Applications/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx/WeddingsAndMore.app/WeddingsAndMore
Expected in: /Applications/Xcode6-Beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.1.sdk/System/Library/Frameworks/CFNetwork.framework/CFNetwork
in /Users/MIkeAspinall 1/Library/Developer/CoreSimulator/Devices/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx/data/Applications/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx/WeddingsAndMore.app/WeddingsAndMore
(lldb)
I'm not sure why this is happening. But the iPhone 5s simulator throws the same error. It just seems to run on the iOS 8.
the settings are set for an ios 7.1 phone
im also using parse.com for my data access
My Phone is Iphone 5s Running ios 8 beta
iphone 4s is running ios 7.1
simulators are running in xcode 6beta
app is set to run on ios 7.1 or above.
i'm using xcode 6beta
hope that clears up what i have
opening code on first view controler
#interface DMKHomeViewController (UIViewcontroller )
#end
#implementation DMKHomeViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
-(BOOL) hasInternet{
Reachability *reach = [Reachability reachabilityWithHostName:#"www.bbc.co.uk"];
NetworkStatus internetStats = [reach currentReachabilityStatus];
if (internetStats == NotReachable) {
UIAlertView *alertOne = [[UIAlertView alloc] initWithTitle:#"No Internet Connection" message:#" A connection To The Internet IS Required While Running This App. Please Reconnect To Continue" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:#"Cancel", nil];
[alertOne show];
}
else {
UIAlertView *alerttwo = [[UIAlertView alloc] initWithTitle:#"Internet Connection Active" message:#"A connection To The Internet IS Required While Running This App. Your Connection Is Live... Thankyou." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:#"Cancel", nil];
[alerttwo show];
}
return YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self hasInternet];
if (![PFUser currentUser]) { // No user logged in
// Create the log in view controller
PFLogInViewController *logInViewController = [[PFLogInViewController alloc] init];
[logInViewController setDelegate:self]; // Set ourselves as the delegate
// Create the sign up view controller
PFSignUpViewController *signUpViewController = [[PFSignUpViewController alloc] init];
[signUpViewController setDelegate:self]; // Set ourselves as the delegate
// Assign our sign up controller to be displayed from the login controller
[logInViewController setSignUpController:signUpViewController];
// Present the log in view controller
[self presentViewController:logInViewController animated:YES completion:NULL];
}
}
// Sent to the delegate to determine whether the log in request should be submitted to the server.
- (BOOL)logInViewController:(PFLogInViewController *)logInController shouldBeginLogInWithUsername: (NSString *)username password:(NSString *)password {
// Check if both fields are completed
if (username && password && username.length != 0 && password.length != 0) {
return YES; // Begin login process
}
[[[UIAlertView alloc] initWithTitle:#"Missing Information"
message:#"Make sure you fill out all of the information!"
delegate:nil
cancelButtonTitle:#"ok"
otherButtonTitles:nil] show];
return NO; // Interrupt login process
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
self.canDisplayBannerAds = YES;
}
// Sent to the delegate to determine whether the sign up request should be submitted to the server.
- (BOOL)signUpViewController:(PFSignUpViewController *)signUpController shouldBeginSignUp:(NSDictionary *)info {
BOOL informationComplete = YES;
// loop through all of the submitted data
for (id key in info) {
NSString *field = [info objectForKey:key];
if (!field || field.length == 0) { // check completion
informationComplete = NO;
break;
}
}
// Display an alert if a field wasn't completed
if (!informationComplete) {
[[[UIAlertView alloc] initWithTitle:#"Missing Information"
message:#"Make sure you fill out all of the information!"
delegate:nil
cancelButtonTitle:#"ok"
otherButtonTitles:nil] show];
}
return informationComplete;
}
// Sent to the delegate when a PFUser is signed up.
- (void)signUpViewController:(PFSignUpViewController *)signUpController didSignUpUser:(PFUser *)user {
[self dismissViewControllerAnimated:YES completion:NULL]; // Dismiss the PFSignUpViewController
}
// Sent to the delegate when the sign up attempt fails.
- (void)signUpViewController:(PFSignUpViewController *)signUpController didFailToSignUpWithError: (NSError *)error {
NSLog(#"Failed to sign up...");
}
// Sent to the delegate when the sign up screen is dismissed.
- (void)signUpViewControllerDidCancelSignUp:(PFSignUpViewController *)signUpController {
NSLog(#"User dismissed the signUpViewController");
}
// Sent to the delegate when a PFUser is logged in.
- (void)logInViewController:(PFLogInViewController *)logInController didLogInUser:(PFUser *)user {
[self dismissViewControllerAnimated:YES completion:NULL];
}
// Sent to the delegate when the log in attempt fails.
- (void)logInViewController:(PFLogInViewController *)logInController didFailToLogInWithError: (NSError *)error {
NSLog(#"Failed to log in...");
}
// Sent to the delegate when the log in screen is dismissed.
- (void)logInViewControllerDidCancelLogIn:(PFLogInViewController *)logInController {
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
DMKHomeViewController *destination = [segue destinationViewController];
destination.interstitialPresentationPolicy = ADInterstitialPresentationPolicyAutomatic;
}
- (IBAction)Logout:(id)sender {
[PFUser logOut];
// Present the log in view controller
if (![PFUser currentUser]) { // No user logged in
// Create the log in view controller
PFLogInViewController *logInViewController = [[PFLogInViewController alloc] init];
[logInViewController setDelegate:self]; // Set ourselves as the delegate
// Create the sign up view controller
PFSignUpViewController *signUpViewController = [[PFSignUpViewController alloc] init];
[signUpViewController setDelegate:self]; // Set ourselves as the delegate
// Assign our sign up controller to be displayed from the login controller
[logInViewController setSignUpController:signUpViewController];
// Present the log in view controller
[self presentViewController:logInViewController animated:YES completion:NULL];
}
}
I am using login with facebook in my app and getting username and profile pic from facebook. I have tested and it is working fine at my end, but apple has rejected it two times. I dont find any error at my end .
This is error by apple team:-
" We still found that your app exhibited one or more bugs, when reviewed on iPad Air running iOS 7.1 and an iPhone 5s running iOS 7.1, on both Wi-Fi and cellular networks, which is not in compliance with the App Store Review Guidelines.
Specifically, when we tap login to Facebook we get message say it wants to connect and when we tap ok it does not advance and connect with Facebook. "
Here is my Code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window = window;
self.login=[[ViewController alloc]init];
_nav = [[UINavigationController alloc] initWithRootViewController:self.login];
self.window.rootViewController = _nav;
[self.window makeKeyAndVisible];
// Override point for customization after application launch.
// Whenever a person opens the app, check for a cached session
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded) {
NSLog(#"Found a cached session");
// If there's one, just open the session silently, without showing the user the login UI
[FBSession openActiveSessionWithReadPermissions:#[#"basic_info", #"email", #"user_likes"]
allowLoginUI:NO
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
// Handler for session state changes
// This method will be called EACH time the session state changes,
// also for intermediate states and NOT just when the session open
[self sessionStateChanged:session state:state error:error];
switch (state) {
case FBSessionStateOpen:
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (error) {
NSLog(#"error:%#",error);
}
else
{
// retrive user's details at here as shown below
NSUserDefaults *storeData=[NSUserDefaults standardUserDefaults];
[storeData setObject:user.id forKey:#"user_id"];
[storeData setObject:user.name forKey:#"name"];
}
}];
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
}];
// If there's no cached session, we will show a login button
} else {
//UIButton *loginButton = [self.login loginButton];
//[loginButton setTitle:#"Log in with Facebook" forState:UIControlStateNormal];
}
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
// This method will handle ALL the session state changes in the app
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error
{
// If the session was opened successfully
if (!error && state == FBSessionStateOpen){
NSLog(#"Session opened");
// Show the user the logged-in UI
[self userLoggedIn];
return;
}
if (state == FBSessionStateClosed || state == FBSessionStateClosedLoginFailed){
// If the session is closed
NSLog(#"Session closed");
// Show the user the logged-out UI
[self userLoggedOut];
}
// Handle errors
if (error){
NSLog(#"Error");
NSString *alertText;
NSString *alertTitle;
// If the error requires people using an app to make an action outside of the app in order to recover
if ([FBErrorUtility shouldNotifyUserForError:error] == YES){
alertTitle = #"Something went wrong";
alertText = [FBErrorUtility userMessageForError:error];
[self showMessage:alertText withTitle:alertTitle];
} else {
// If the user cancelled login, do nothing
if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryUserCancelled) {
NSLog(#"User cancelled login");
// Handle session closures that happen outside of the app
} else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryAuthenticationReopenSession){
alertTitle = #"Session Error";
alertText = #"Your current session is no longer valid. Please log in again.";
[self showMessage:alertText withTitle:alertTitle];
// For simplicity, here we just show a generic message for all other errors
// You can learn how to handle other errors using our guide: https://developers.facebook.com/docs/ios/errors
} else {
//Get more error information from the error
NSDictionary *errorInformation = [[[error.userInfo objectForKey:#"com.facebook.sdk:ParsedJSONResponseKey"] objectForKey:#"body"] objectForKey:#"error"];
// Show the user an error message
alertTitle = #"Something went wrong";
alertText = [NSString stringWithFormat:#"Please retry. \n\n If the problem persists contact us and mention this error code: %#", [errorInformation objectForKey:#"message"]];
[self showMessage:alertText withTitle:alertTitle];
}
}
// Clear this token
[FBSession.activeSession closeAndClearTokenInformation];
// Show the user the logged-out UI
[self userLoggedOut];
}
}
// Show the user the logged-out UI
- (void)userLoggedOut
{
// Set the button title as "Log in with Facebook"
// UIButton *loginButton = [self.login loginButton];
//[loginButton setTitle:#"Log in with Facebook" forState:UIControlStateNormal];
// Confirm logout message
//[self showMessage:#"You're now logged out" withTitle:#""];
}
// Show the user the logged-in UI
- (void)userLoggedIn
{
// Set the button title as "Log out"
// UIButton *loginButton = self.login.loginButton;
//[loginButton setTitle:#"Log out" forState:UIControlStateNormal];
FrontViewController *v=[[FrontViewController alloc]init];
RearViewController *rearViewController = [[RearViewController alloc] init];
UINavigationController *frontNavigationController = [[UINavigationController alloc] initWithRootViewController:v];
UINavigationController *rearNavigationController = [[UINavigationController alloc] initWithRootViewController:rearViewController];
SWRevealViewController *revealController = [[SWRevealViewController alloc] initWithRearViewController:rearNavigationController frontViewController:frontNavigationController];
revealController.delegate = self;
[self.nav pushViewController:revealController animated:YES];
[self showMessage:#"You're now logged in" withTitle:#"Welcome!"];
}
// Show an alert message
- (void)showMessage:(NSString *)text withTitle:(NSString *)title
{
[[[UIAlertView alloc] initWithTitle:title
message:text
delegate:self
cancelButtonTitle:#"OK!"
otherButtonTitles:nil] show];
}
// During the Facebook login flow, your app passes control to the Facebook iOS app or Facebook in a mobile browser.
// After authentication, your app will be called back with the session information.
// Override application:openURL:sourceApplication:annotation to call the FBsession object that handles the incoming URL
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
return [FBSession.activeSession handleOpenURL:url];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Handle the user leaving the app while the Facebook login dialog is being shown
// For example: when the user presses the iOS "home" button while the login dialog is active
[FBAppCall handleDidBecomeActive];
}
In My View Controller
- (IBAction)buttonTouched:(id)sender
{
// If the session state is any of the two "open" states when the button is clicked
if (FBSession.activeSession.state == FBSessionStateOpen
|| FBSession.activeSession.state == FBSessionStateOpenTokenExtended) {
// Close the session and remove the access token from the cache
// The session state handler (in the app delegate) will be called automatically
[FBSession.activeSession closeAndClearTokenInformation];
// If the session state is not any of the two "open" states when the button is clicked
} else {
// Open a session showing the user the login UI
// You must ALWAYS ask for basic_info permissions when opening a session
[FBSession openActiveSessionWithReadPermissions:#[#"basic_info", #"email", #"user_likes"]
allowLoginUI:YES
completionHandler:
^(FBSession *session, FBSessionState state, NSError *error) {
// Retrieve the app delegate
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
// Call the app delegate's sessionStateChanged:state:error method to handle session state changes
[appDelegate sessionStateChanged:session state:state error:error];
switch (state) {
case FBSessionStateOpen:
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (error) {
NSLog(#"error:%#",error);
}
else
{
// retrive user's details at here as shown below
NSLog(#"FB user first name:%#",user.first_name);
NSUserDefaults *storeData=[NSUserDefaults standardUserDefaults];
[storeData setObject:user.id forKey:#"user_id"];
[storeData setObject:user.name forKey:#"name"];
}
}];
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
}];
}
}
Is your app on developer.facebook.com public and available for all users?
Status should look like this:
In other case if your app has status Developer Mode then other users can't authorise by Facebook.
I have exactly the same issue. Although it's a Flutter app, but the use-case is the same.
On my end, everything works as expected
Fb app has iOS and Bundle ID set correctly
FB app is public
But the Apple review team still rejects it. I asked for more Screenshots, which they provided, AND the screenshots clearly show the "continue" dialog of the FB-popup. So I don't understand why they rejected it.
I have problem with facebook Login..I integrated Facebook into my app.First time when user wants to login it is showing login page,but from next time it is going to page "You have already authorised APP_NAME".
I checked for Scrumptious tutorial which is the sample which I got from Facebook SDK.and it is also working like same.
I want to login from different user,I dont want that page "You have already authorised APP_NAME" every time.
How to solve this.
Try this code in your app delegate class.
It checks whether the session is open or not and clears your login credentials from the device cache when you close the connection.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
LoginVC *loginScreen=[[LoginVC alloc]initWithNibName:#"LoginVC" bundle:nil];
navigationController=[[UINavigationController alloc]initWithRootViewController:loginScreen];
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
self.window.rootViewController=self.navigationController;
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
// See if we have a valid token for the current state.
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded) {
[self openSession];
// To-do, show logged in view
} else {
// No, display the login page.
[self showLoginView];
}
return YES;
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen: {
UIViewController *topViewController =
[self.navigationController topViewController];
if ([[topViewController presentedViewController]
isKindOfClass:[LoginVC class]]) {
[topViewController dismissViewControllerAnimated:YES completion:nil];
}
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// be looking at the root view.
[self.navigationController 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];
}];
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
return [FBSession.activeSession handleOpenURL:url];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
// We need to properly handle activation of the application with regards to Facebook Login
// (e.g., returning from iOS 6.0 Login Dialog or from fast app switching).
[FBSession.activeSession handleDidBecomeActive];
}
I hope this code will be helpful.