UILabel becomes null after facebook login (UILabel dosen't update) - iphone

I am working on adding facebook SSO and the SDK to my project. All of my main facebook code is in my AppDelegate.m and AppDelegate.h.
In my view controller [[[UIApplication sharedApplication] delegate] performSelector:#selector(callLogin)]; is called when I press a button.
The callLogin method in my AppDelegate.m looks like this:
- (void)callLogin{
facebook = [[Facebook alloc] initWithAppId:#"XXXXX" andDelegate:self];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"]
&& [defaults objectForKey:#"FBExpirationDateKey"]) {
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
if (![facebook isSessionValid]) {
[facebook authorize:nil];
}
}
Then in my - (void)fbDidLogin method I call the method setInfo which is located in my viewcontroller.
//this method is located in AppDelegate.m
- (void)fbDidLogin {
NSLog(#"FACEBOOK DID LOGIN");
ViewController * vc = [[ViewController alloc]init];
[vc setInfo];
}
Finally, here is my -(void)setInfo code which is located in ViewController.m
-(void)setInfo{
infoL.text = [NSString stringWithFormat: #"Connected to Facebook!"];
NSLog(#"%#",infoL);
//NSLog returns null
}
From setInfo I am unable to change the label and NSLog returns that infoL is null. I can update the label through methods like ViewDidLoad, but not setInfo.
What am I doing wrong and how can I fix this?

The view controller won't get updated because you just created some random instance of the class that is not on your navigation stack. I suppose you could call
[ self.viewController setInfo ]
assuming that is the property name for the vc you pushed on the stack in applicationDidFinishLaunchingWithOptions although this wouldn't be considered great design. Id factor Facebook delegate stuff out out app delegate, create a Facebook controller singleton class that your view controller can feed off

I assume that infoL represents a UILabel. Do you create this label in code or is an outlet that is created automatically?
If you create infoL in code, where is it allocated/initted? Is it non-nil at any time before your setInfo method runs?

Related

Objective c. Login user using storyboard

I have an storyboard with three view controllers, the init view with a button Init, the login view controller and the list view controller. When I click in the button init in the first view controller, I would like to verify whether the user logged in in order to switch to the login view or to the list view. How could I implement this using segues (segue conditionals??)
You could do something like this
BOOL isLoggedIn = [[NSUserDefaults standardUserDefaults] boolForKey:#"isLoggedIn"];
NSString *headingStoryboardID = isLoggedIn ? #"YourAlreadyLoggedInVC_ID" : #"YourLoginVC_ID";
if([headingStoryboardID isEqualToString:#"YourAlreadyLoggedInVC_ID"]) {
AlreadyLoggedInClass *vc1 = (AlreadyLoggedInClass *)[self.storyboard instantiateViewControllerWithIdentifier:#"YourAlreadyLoggedInVC_ID"];
[self presentViewController:vc2 animated:YES completion:nil];
} else {
LoginViewController *vc2 = (LoginViewController *)[self.storyboard instantiateViewControllerWithIdentifier:#"YourLoginVC_ID"];
[self presentViewController:vc2 animated:YES completion:nil];
}
OBS: Ugly and uncompiled code but hope the concept gets across.
EDIT DUE TO COMMENT
To perform a push segue you call
[self.navigationController pushViewController:vc1 animated:YES];
instead.
You can Store your login value in user default when user login like this
in LOginViewController
-(void) doLogin
{
NSString * str = #"Loged In";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:str forKey:#"login"];
[defaults synchronize];
}
And in first view controller check whether this NSdefault value is nil or not.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *userLogIn = [defaults objectForKey:#"login"];
if (userLogIn.length !=0) {
//then user Loged in
}else
{
//then user not Loged in
}
This code is just example you can change it acording to your need.

What is the perfect way to make a logout from IOS app?

The below code is working but has a bug. The scenario is that, I begin by logging in to enter the app system. Once the login has succeeded, the app will set UserDefaults (UserId). After that, I can navigate the app views with stored UserId. Once I go to settings and tab logout, that will clean UserId and go to login view.
The BUG: When I login again to the app and click the home button to go to iPhone desktop and close the app, and return to open it again it still storing the UserId. So, if I go to the setting and log out that will clean UserId and will not go to login view. I don't know why.
The code:
- (IBAction)resetKeychain:(id)sender {
UIActionSheet *actionSheet = [[UIActionSheet alloc]
initWithTitle:#"Are you sure you want to logout?"
delegate:self
cancelButtonTitle:#"Cancel"
destructiveButtonTitle:#"Logout"
otherButtonTitles:nil];
actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
[actionSheet showFromTabBar:self.tabBarController.tabBar];
[actionSheet release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex ==0) {
//logout
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
//delete user ID fro user Defaults
[defaults setObject:nil forKey:#"UserId"];
//redirect to login view
NewClassMoonAppDelegate * appsDelegate =[[UIApplication sharedApplication] delegate];
[appsDelegate.window addSubview:[appsDelegate.login view]];
}
}
From what I can interpret from you question, which needs to be formatted and made coherent by the way, I believe that:
a) your #"UserID" value is not syncing with NSUserDefaults because you are not calling the -synchronize method. NSUserDefaults will update its in-memory key-value store, but will not write it to disk meaning that it's lost at an arbitrary time.
b) The fact that it is not going to the loginView could be to do with any few reasons, most likely that it is already a subview of your UIWindow. So, instead of reusing the login property in your app delegate, create a new instance variable of the View Controller, and set that as the rootViewController instead.
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:nil forKey:#"UserId"];
[defaults synchronize];
//redirect to login view
NewClassMoonAppDelegate * appsDelegate =[[UIApplication sharedApplication] delegate];
LoginViewController *login = [[LoginViewController alloc] initWithNibName...];
[appsDelegate.window setRootViewController:nil];
[appsDelegate.window setRootViewController:login];
}
}
Swift:
From max_'s answer with some changes:
let objectsToSave: [String] = [obj1, obj2, obj3]
for key in objectsToSave {
NSUserDefaults.standardUserDefaults().removeObjectForKey(key)
}
let appsDelegate = UIApplication.sharedApplication().delegate
let storyboard = UIStoryboard(name: "MainStoryboard", bundle: nil)
let newLoginVC: LoginViewController = storyboard.instantiateInitialViewController() as! LoginViewController
appsDelegate?.window!!.rootViewController = nil
appsDelegate?.window!!.rootViewController = newLoginVC
EDIT: The only changes I've made are just that I initialize newLoginVC through Storyboards instead of initWitName.
Make property of UINavigation controller and synthesize it, And write below code on logout button
AppDelegate * appDelegateObj =[[UIApplication sharedApplication] delegate];
login *loginObj = [[login alloc]initWithNibName:#"login" bundle:nil];
[appDelegateObj.window setRootViewController:nil];
navObj=[[UINavigationController alloc]initWithRootViewController:loginObj];
[appDelegateObj.window setRootViewController:navObj];

Problems displaying view controller when local notification received on iPhone

The following code is my latest attempt to display a view controller when my application receives a particular local notification:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
NSLog(#"Notification Received. UserInfo: %#", [notification.userInfo valueForKey:#"notificationType"]);
if ([[notification.userInfo valueForKey:#"notificationType"] isEqualToString:#"backup"])
{
NSLog(#"Backup notification received.");
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"Yes" forKey:#"shouldBackup"];
[defaults synchronize];
SettingsViewController *vc = [self.window.rootViewController.tabBarController.viewControllers objectAtIndex:3];
[self.window.rootViewController.tabBarController.navigationController pushViewController:vc animated:NO];
}
else
{
NSLog(#"Did receive notification: %#, set for date:%# .", notification.alertBody, notification.fireDate);
}
}
I then have this piece of code which I use in the viewDidAppear method to determine wether or not to perform the backup:
if ([[defaults objectForKey:#"shouldBackup"] isEqualToString:#"Yes"]){
[defaults setObject:#"No" forKey:#"shouldBackup"];
[defaults synchronize];
HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:HUD];
HUD.delegate = self;
HUD.labelText = #"Backing Up Your Data..";
HUD.minSize = CGSizeMake(135.f, 135.f);
[HUD showWhileExecuting:#selector(performBackup) onTarget:self withObject:nil animated:YES];
}
However, it appears that viewDidAppear is never called, can anyone explain what it is I'm doing wrong? I've tried several different approaches now and I just can't seem to get it to work..
Thanks,
Tysin
You need to push the SettingsViewController onto the stack from a NavigationController in order for its delegate methods to be called (in this case viewDidAppear). It seems that your root view controller is a TabBarController. In this case add the UINavigationControllerDelegate to your root VC, more info on what to do next can be found here http://www.touchthatfruit.com/viewwillappear-and-viewdidappear-not-being-ca
Also, are you sure viewDidAppear is not getting called or just the code within it is not getting called? Add a breakpoint to find out.
Lastly, do you haveĀ [super viewDidAppear:animated]; in the viewDidAppear method of SettingsViewController?
If all else fails you can always call viewDidAppear manually from the parent view controller :)
Hope this helps!

IF statment not checking condition on first run

I'm new to programming and I have an app that has a login view on start up and request the user to enter their name which is used throughout out the program. Once they enter their name and log in they are presented with the main menu view. Their name is saved using NSUserdefaults.
The idea is that they will only have to login once (or again if they logout) so they should only see the login view the first time they run the app however once the app is started again it still shows the login screen and also you have to press the login button twice before you are taken to the main menu.
I know that the app is storing the details because it is used thought the app but I cant work out why. Here is my code. If someone could help it would be greatly appreciated.
-(IBAction)LogInButton:(id)sender
{
NSString *tempStr = [[NSUserDefaults standardUserDefaults] objectForKey:#"UserName"];
if(tempStr.length==0)
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:Name.text forKey:#"UserName"];
[prefs synchronize];
LogInView *Logview = [[LogInView alloc] initWithNibName:#"LogInView" bundle:nil];
[self presentModalViewController:Logview animated:YES];
}
else
{
MainMenuView *mainview = [[MainMenuView alloc] initWithNibName:#"MainMenuView" bundle:nil];
[self presentModalViewController:mainview animated:YES];
}
}
Judging by your description what you want is
On viewDidLoad check to see if the user is logged in
If YES show the MainMenu
If NO show the LogInView
The code may look like this
- (void)viewDidLoad
{
[super viewDidLoad];
[self showCorrectController];
}
The show correct controller method could look like this
- (void)showCorrectController
{
UIViewController *viewController = nil;
if ([self isLoggedIn]) {
viewController = [[MainMenuView alloc] init];
} else {
viewController = [[LogInView alloc] init];
}
[self presentModalViewController:viewController animated:YES];
[viewController release]; viewController = nil;
}
A convenience method is called isLoggedIn which looks like this
- (BOOL)isLoggedIn
{
// The double negation just means we get a boolean response
return !![[NSUserDefaults standardUserDefaults] objectForKey:#"UserName"];
}
Now edit your original method to something like this
-(IBAction)LogInButton:(id)sender
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:Name.text forKey:#"UserName"];
[prefs synchronize];
[self showCorrectController];
}
There are quite a few things that could be done to tidy this up a lot but this should be a start to get you going.
A word of caution on your naming of things. The convention is to start method and variable names with lowercased letters. Classes and constants start with uppercase letters.
It looks like the first time in:
The login screen shows up
The user presses login (and this method you're showing gets called)
The saved value isn't initially set, so this evaluates to true: if(tempStr.length==0)
You save the new value
You display another login screen
But I don't think you're showing all the code. What runs when the app launches?

Can I call presentModalViewController in viewDidLoad..?

In my iPhone app I have HomeViewController and ContentViewController. I am saving the values in ContentViewController by using NSUserDefaults
and based on saved values I will load the ContentView instead of HomeView when the app is restarted. if there r no values in the NSUserDefaults it displays the HomeView.
in HomeView I have some buttons..it's like this.. each button is for a book so in contentView all the page nos (in the bottom in a scroll view in ContentView) will be displayed if I click on a page no it displays the text in the above label of ContentView.if the user closes the app in contentView, the page no and book no will be saved...if the user clicks on home button all the information will be deleted.
In the Homeview im checking the NSUserDefaults, if it contains values it should display that exact page of that book
the following is the code...
//HomeViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
contentViewController = [[ContentViewController alloc] initWithNibName:#"ContentView" bundle:nil];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSLog(#"...%d,%d,%d",[prefs integerForKey:#"Stage"],[prefs integerForKey:#"Stimulus"],[prefs integerForKey:#"Card"]);
if(!([prefs integerForKey:#"Stage"] ==0 && [prefs integerForKey:#"Stimulus"] ==0 && [prefs integerForKey:#"Card"] ==0)){
[contentViewController setCurrentState:[prefs integerForKey:#"Stage"]];
[contentViewController setCurrentStimulus:[prefs integerForKey:#"Stimulus"]];
[contentViewController setCurrentCard:[prefs integerForKey:#"Card"]];
[self presentModalViewController:contentViewController animated:YES];
}
}
but it's displaying the homeview.
Try using the method viewDidAppear shown below instead of viewDidLoad
- (void)viewDidAppear:(BOOL)animated
{
contentViewController = [[ContentViewController alloc] initWithNibName:#"ContentView" bundle:nil];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSLog(#"...%d,%d,%d",[prefs integerForKey:#"Stage"],[prefs integerForKey:#"Stimulus"], [prefs integerForKey:#"Card"]);
if(!([prefs integerForKey:#"Stage"] ==0 && [prefs integerForKey:#"Stimulus"] ==0 && [prefs integerForKey:#"Card"] ==0))
{
[contentViewController setCurrentState:[prefs integerForKey:#"Stage"]];
[contentViewController setCurrentStimulus:[prefs integerForKey:#"Stimulus"]];
[contentViewController setCurrentCard:[prefs integerForKey:#"Card"]];
[self presentModalViewController:contentViewController animated:YES];
}
}