fbconnect logout is not working perfectly - iphone

i have integrated Fbconnect in LoginViewController.I want to logout the session from another view controller .. How i can do this ?
I tried this ..
LoginViewController *obj1 = [[LoginViewController alloc] init];
[obj1._session logout];
[obj1._session.delegates removeObject: self];
It removing the session..But wen i go to LoginViewController the button is showing logout.But when i quit application and run it, the image is updated.
In LoginViewController i have
#interface LoginViewController : UIViewController <FBDialogDelegate, FBSessionDelegate, FBRequestDelegate>{
IBOutlet UITextField *txtUsername;
IBOutlet UITextField *txtPassword;
IBOutlet UILabel *lblMessage;
IBOutlet FBLoginButton* _loginButton;
FBSession* _session;
}
#property (nonatomic, retain) FBSession *_session;
and am synthesizing it #synthesize _session;
....What else i have to do ?
Somebody please help me..am very new to Iphone application and objective c

I got the answer ..My Friend helped me.. i want to share it...
simply
import "FBConnect.h"
in ur second view controller
then .......
FBSession *session = [FBSession
session]; [session logout];
It works fine

-(void)clickfb:(id)sender
{
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie* cookie in
[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
[cookies deleteCookie:cookie];
}
[self showLoggedOut:YES];
}
(void) showLoggedOut:(BOOL)clearInfo {
//[self.navigationController setNavigationBarHidden:YES animated:NO];
// // Remove saved authorization information if it exists and it is
// // ok to clear it (logout, session invalid, app unauthorized)
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (clearInfo && [defaults objectForKey:#"FBAccessTokenKey"]) {
[defaults removeObjectForKey:#"FBAccessTokenKey"];
[defaults removeObjectForKey:#"FBExpirationDateKey"];
[defaults synchronize];
//
// // Nil out the session variables to prevent
// // the app from thinking there is a valid session
AppDelegate *delegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
if (nil != [[delegate facebook] accessToken]) {
[delegate facebook].accessToken = nil;
}
if (nil != [[delegate facebook] expirationDate]) {
[delegate facebook].expirationDate = nil;
}
}
}

Related

Facebook in iPhone app

I am working on an iPhone app,in this i have an option for sharing my posts with face book(i am just passing the user id of facebook user and my server side developer do the posting part)
I am able to take the user id while log in in face book
But problem is-after the user authenticate from facebook,"post on your behalf" is not coming in the app
(i am using ios6 SDK)
(i have created my app in facebook with checked that public_action from graph)
I have gone through the tutorials(scrumptious) given in facebook developer page,but could not make it
Here are my code-If any one find the error or missing part,please help me to clear that
AppDelegate.h
#import <FacebookSDK/FacebookSDK.h>
#class ViewController;
#interface AppDelegate : UIResponder
#property (strong, nonatomic) FBSession *session;
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) ViewController *viewController;
#property (strong,nonatomic) IBOutlet UINavigationController *navBar;
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI;
#end
AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
#define APP_ID #"fd725FDE45a44198a5b8ad3f7a0ffa09"
#implementation AppDelegate
#synthesize session = _session;
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [self.session handleOpenURL:url];
}
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"user_location",
#"user_birthday",
#"user_likes",
#"email",
#"publish_action",
nil];
return [FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:allowLoginUI
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: {
FBCacheDescriptor *cacheDescriptor = [FBFriendPickerViewController cacheDescriptor];
[cacheDescriptor prefetchAndCacheForSession:session];
}
break;
case FBSessionStateClosed: {
[FBSession.activeSession closeAndClearTokenInformation];
[self performSelector:#selector(showLoginView)
withObject:nil
afterDelay:0.5f];
}
break;
case FBSessionStateClosedLoginFailed: {
[self performSelector:#selector(showLoginView)
withObject:nil
afterDelay:0.5f];
}
break;
default:
break;
}
}
#end
InviteFriendViewController.h
#interface InviteFriendViewController :
-(IBAction)fbfrnds:(id)sender;
- (void)updateView;
#end
InviteFriendViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
[self.navigationController setNavigationBarHidden:YES];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
userid = [defaults objectForKey:#"userid"];
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (!appDelegate.session.isOpen) {
appDelegate.session = [[FBSession alloc] init];
if (appDelegate.session.state == FBSessionStateCreatedTokenLoaded) {
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
[self updateView];
}
];
}
}
}
-(void)facebookReteriveInformation:(NSDictionary *)dictnry{
FriendlistViewController *friends = [[FriendlistViewController alloc]initWithNibName:#"FriendlistViewController" bundle:nil];
friends.token = string;
[self.navigationController pushViewController:friends animated:YES];
}
-(IBAction)fbfrnds:(id)sender{
sharedClass=[SharedClass sharedInstance];
appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (appDelegate.session.isOpen) {
[self updateView];
} else {
if (appDelegate.session.state != FBSessionStateCreated) {
appDelegate.session = [[FBSession alloc] init];
}
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
[self updateView];
}];
}
NSLog(#"string issss %#",string);
}
- (void)updateView {
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (appDelegate.session.isOpen) {
string = [NSString stringWithFormat:#"%#",
appDelegate.session.accessToken];
NSLog(#"string issss %#",string);
NSString *urlstrng;
if(flag == 1){
urlstrng = [NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=%#",
string];
[self dataFetching:urlstrng];
}
} else {
string = [NSString stringWithFormat:#"%#",
appDelegate.session.accessToken];
NSString *urlstrng;
if(flag == 1){
urlstrng = [NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=%#",
string];
[self dataFetching:urlstrng];
}
}
}
-(void)dataFetching:(NSString*)strng1{
NSURL *url = [NSURL URLWithString:strng1];
ProfileConnector *obj = [[ProfileConnector alloc] init];
obj.delegate1 = self;
[obj parsingJson:url];
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void) performPublishAction:(void (^)(void)) action {
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
[FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
}
}];
} else {
action();
}
}
}
#end
Since you're using the 3.1 version of Facebook SDK, openActiveSessionWithPermissions:allowLoginUI:completionHandler: is not supposed to be used and the old way of doing it does not seem to be functional anymore; from the 3.1 migration documentation;
...you will need to remove usage of openActiveSessionWithPermissions:allowLoginUI:completionHandler: and replace it with openActiveSessionWithReadPermissions:allowLoginUI:completionHandler: (or even more simply, openActiveSessionWithAllowLoginUI).
Later, when your app needs to publish back to Facebook, you should use reauthorizeWithPublishPermissions:defaultAudience:completionHandler: to seek the additional permissions.
Even more details available at the migration docs.

Repeating authorization Window

I'm using Xcode 4.3.1
In my app I try to use Facebook SSO.My requirement is at the first time the app should ask for the authorization after that it should check whether the app is authorized by the user and should move to the next process(even after the task in the device is cancelled).I don't that authorization window to repeat again and again.
in Appdelegate:
facebook=[[Facebook alloc]initWithAppId:appid andDelegate:first];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSLog(#"%#Defaults:",[defaults objectForKey:#"FBAccessTokenKey"]);
if ([defaults objectForKey:#"FBAccessTokenKey"]
&& [defaults objectForKey:#"FBExpirationDateKey"])
{
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
accessToken=facebook.accessToken;
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
date=facebook.expirationDate;
}
In my view Controller:
-(IBAction)LoginClick:(id)sender
{
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
[defaults1 setObject:xapp.facebook.accessToken forKey:#"FBAccessTokenKey"];
[defaults1 setObject:xapp.facebook.expirationDate forKey:#"FBExpirationDateKey"];
[defaults1 synchronize];
if (![xapp.facebook isSessionValid])
{
permissions = [[NSArray alloc] initWithObjects:#"read_stream",#"publish_stream", nil];
[xapp.facebook authorize:permissions];
}
else if([xapp.facebook isSessionValid])
{
NSLog(#"Hiii");
permissions=nil;
[xapp.facebook authorize: nil];
}
}
How can I make the authorization window to not appear after the app is authorized...
Alright, you are asking for permissions each time you run your app in your AppDelegate. To prevent this, you have to make a separate method for permission that will be granted only if the login button is pressed and checked if the app is permitted or not. Try this in your AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self.window makeKeyAndVisible];
facebook = [[Facebook alloc] initWithAppId:#"YOURAPPID" andDelegate:self];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"] && [defaults objectForKey:#"FBExpirationDateKey"])
{
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
return YES;
}
Above your fbDidLogIn method in your AppDelegate add this method, you have to add the FBUser protocol to your AppDelegate:
-(void)fbLogin:(id<FBUser>)_listener
{
listener = _listener;
if(![facebook isSessionValid])
{
NSArray* permissions = [[NSArray arrayWithObjects:
#"publish_stream",
#"read_stream",
nil] retain];
[facebook authorize:permissions];
}
else
{
[listener facebookDidLogin];
}
}
And in your ViewController modify your login method like this:
-(IBAction)LoginClick:(id)sender
{
YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate fbLogin:self];
}
The FBUser.h is a custom header file that defines the protocol method -(void)fbDidLogIn. This is just to make sure that, the app does not ask login permission each it time launches.
#import <Foundation/Foundation.h>
#protocol FBUser <NSObject>
-(void)facebookDidLogin;
#end
By this, the login method is only called when the app needs to login to Facebook and do something.
Hope this helps you. Cheers!

NSUserDefaults doubts in iphone SDK

I am integrating twitter in my app for sharing a text. My architecture of twitter integration is I have two Button _btnTwitter and _btntwitteLogout and when the user successfully login the twitter his name will display in _btntwitterLogout as title.
When the user tap the _btntwitterLogout it logs out the twitter and logout button hides and login button comes.every thing went ok.but when the user tap the login button(_btnTwitter) the Twitter login popup cmes for login purpose,here is the problem that am facing ,when the popup comes the user tap the cancel button of that popup the popup disappears and here the previous username of the user in the logout button.it didn't changes. I have put user defaults to check.
-(IBAction)_clickbtnTwitter:(id)sender
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"Twitter_logged"];
[_btntwitterLogeout setTitle:nil forState:UIControlStateNormal];
_btntwitterLogeout.hidden = NO;
_btnTwitter.hidden=YES;
if (_engine) return;
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate: self];
_engine.consumerKey = kOAuthConsumerKey;
_engine.consumerSecret = kOAuthConsumerSecret;
UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];
if (controller)
[self presentModalViewController: controller animated: YES];
else {
[_engine sendUpdate: [NSString stringWithFormat: #"Already Updated. %#", [NSDate date]]];
}
}
}
then logout code
-(IBAction)_clickbtntwitterlogeout:(id)sender
{
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"Twitter_logged"];
crosstwitterimage.hidden = YES;
[_btntwitterLogeout setTitle:nil forState:UIControlStateNormal];
_btntwitterLogeout.hidden = YES;
_btnTwitter.hidden=NO;
_btnTwittermain.enabled = NO;
[_engine clearAccessToken];
[_engine clearsCookies];
[_engine setClearsCookies:YES];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"authData"];
[[NSUserDefaults standardUserDefaults]removeObjectForKey:#"authName"];
NSLog(#"%#",[[NSUserDefaults standardUserDefaults]valueForKey:#"authName"]);
NSLog(#"%#",[[NSUserDefaults standardUserDefaults]valueForKey:#"authData"]);
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"Twitter_logged"];
[_engine release];
_engine=nil;
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
NSString* domainName = [cookie domain];
NSRange domainRange = [domainName rangeOfString:#"twitter"];
if(domainRange.length > 0)
{
[storage deleteCookie:cookie];
}
}
}
in viewwillappear
BOOL logged = [[NSUserDefaults standardUserDefaults] boolForKey:#"Twitter_logged"];
;
if (logged == YES) {
_btnTwitter. hidden = YES;
_btntwitterLogeout.hidden = NO;
crosstwitterimage.hidden = NO;
_btnTwittermain.enabled =YES;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//Checks if there is a saved User Name
if([defaults objectForKey:#"kTwitterUserName"])
{
NSString *username = [defaults objectForKey:#"kTwitterUserName"];
[_btntwitterLogeout setTitle:username forState:UIControlStateNormal];
crosstwitterimage.hidden = NO;
}
}
else
{
_btnTwitter. hidden = NO;
crosstwitterimage.hidden = YES;
[_btntwitterLogeout setTitle:nil forState:UIControlStateNormal];
_btnTwittermain.enabled =NO;
crosstwitterimage.hidden = YES;
}
but when i tap the cancel button in loginwindow of twitter,an comes back the username with the logout button shows ,if the user is already logedout from twitter.
is there any problem in my code.
thanks in advance.
EDIT
#pragma mark SA_OAuthTwitterEngineDelegate
- (void) storeCachedTwitterOAuthData: (NSString *) data forUsername: (NSString *) username {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: data forKey: #"authData"];
[defaults synchronize];
}
- (NSString *) cachedTwitterOAuthDataForUsername: (NSString *) username {
return [[NSUserDefaults standardUserDefaults] objectForKey: #"authData"];
}
#pragma mark SA_OAuthTwitterControllerDelegate
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
NSLog(#"Authenicated for %#", username);
[_btntwitterLogeout setTitle:username forState:UIControlStateNormal];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:username forKey:#"kTwitterUserName"];
[defaults synchronize];
}
- (void) OAuthTwitterControllerFailed: (SA_OAuthTwitterController *) controller {
NSLog(#"Authentication Failed!");
}
- (void) OAuthTwitterControllerCanceled: (SA_OAuthTwitterController *) controller {
NSLog(#"Authentication Canceled.");
}
#pragma mark TwitterEngineDelegate
- (void) requestSucceeded: (NSString *) requestIdentifier {
NSLog(#"Request %# succeeded", requestIdentifier);
}
- (void) requestFailed: (NSString *) requestIdentifier withError: (NSError *) error {
NSLog(#"Request %# failed with error: %#", requestIdentifier, error);
}
Yes there is a problem. Whenever you hit the _btnTwitter, you are setting the Twitter_logged to yes. That's not correct. You should only set it to yes when there is a successful login. That is when the user has NOT hit cancel on the twitter login window.
In other words, you need to set the Twitter_logged to YES once the user has actually logged in, not when the user clicked on the button _btnTwitter
Seems like SA_OAuthTwitterController has a delegate property pointing to self. You should handle code to set Twitter_logged YES in that delegate method.
Hope that helps.
Edit:
Given the latest code here is where you should add the NsUserDefaults data
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
NSLog(#"Authenicated for %#", username);
[_btntwitterLogeout setTitle:username forState:UIControlStateNormal];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:username forKey:#"kTwitterUserName"];
[defaults setBool:YES forKey:#"Twitter_logged"]; // Right here - mbh
[defaults synchronize];
}

How to make my method run when the view re-load

I want to create a login button. When I click it the facebook launches, I accept my application, the Facebook application closes and my application reloads. My problem is that the second time my application starts, after accepting on Facebook, I cannot find where to disable the login button.
I wrote this code:
-(IBAction) login:(id)sender;
{
AutoAppDelegate *delegate = (AutoAppDelegate *) [[UIApplication sharedApplication] delegate];
// Check and retrieve authorization information
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"]
&& [defaults objectForKey:#"FBExpirationDateKey"]) {
[delegate facebook].accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
[delegate facebook].expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
if (![[delegate facebook] isSessionValid]) {
[delegate facebook].sessionDelegate = self;
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"user_likes",
#"read_stream",
nil];
[[delegate facebook] authorize:permissions];
} else {
logIn.hidden=YES;
lbl.text=#"";
lbl.text=#"Connected";
[self showLoggedIn];
}
}
- (void) showLoggedIn {
NSLog(#"11 Logged In ");
lbl.text=#"";
lbl.text=#"Connected";
}
- (void) showLoggedOut {
NSLog(#"11 Not Logged In ");
lbl.text=#"";
lbl.text=#"Not Connected";
}
- (void) viewWillAppear:(BOOL)animated
{
//[self.navigationController setNavigationBarHidden:YES animated:animated];
[super viewWillAppear:animated];
AutoAppDelegate *delegate = (AutoAppDelegate *) [[UIApplication sharedApplication] delegate];
// Check and retrieve authorization information
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"]
&& [defaults objectForKey:#"FBExpirationDateKey"]) {
[delegate facebook].accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
[delegate facebook].expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
if (![[delegate facebook] isSessionValid]) {
// [self showLoggedOut];
NSLog(#"Not Connected");
} else {
// [self showLoggedIn];
NSLog(#"Connected");
}
}
The viewWillAppear works the first time, but when I give permissions in the Facebook application, my application restarts but not viewWillAppear method!
You need to put the code in your application delegate (applicationWillEnterForeground), as it's the only thing to get notified automatically when the app is re-opened (your view is not necessarily re-drawn).
Have you tried to calling setNeedsDisplay on the view after the Facebook thing is done?

update NSUserDefaults between two view controllers

First off, I am a complete noob, so please be gentle when explaining. I have a program that loads a webpage (UIWebview) on the first view controller. The first view controller checks to see if the NSUserDefaults contains "jdoe1234" for the UserName. If it does, it loads the first webpage, if it has something different, it loads a second webpage. I also have an information button that flips to the second view controller.
On the second view controller, a person can type in a username and password and click the Done button which flips them back to the first controller view. Inside the done button code, I am updating the NSUserDefaults to include the username and password textbox values.
My problem is when the person flips back to the first view controller, the webpage is not refreshing with the values that the person just typed in and saved. When I close the program and open it again, the new values show correctly. I have searched and tried different examples, but I am unable to get it to work. I have listed my code below. I appreciate any help on this.
FirstViewController.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
#interface FirstViewController : UIViewController {
IBOutlet UIWebView *loadInitialGradebook;
IBOutlet UILabel *labelUserName;
}
- (IBAction)infoButtonPressed:(id)sender;
-(IBAction)refreshWebView;
#property (nonatomic, retain) UILabel *labelUserName;
#end
FirstViewController.m
#import "FirstViewController.h"
#import "SecondViewController.h"
#implementation UACCHViewController
#synthesize labelUserName;
- (IBAction)infoButtonPressed:(id)sender;
{
SecondViewController *second = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
second.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:second animated:YES];
}
- (IBAction)refreshWebView {
[loadInitialWebView reload];
}
// Start Strip URL of spaces & funky characters
- (NSString *)urlEncodeValue:(NSString *)str
{
NSString *result = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8);
return [result autorelease];
}
// End Strip URL of spaces & funky characters
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
labelUserName.text = [[NSUserDefaults standardUserDefaults] stringForKey:#"txtFieldUserName"];
// Start Load WebView
if (![[NSUserDefaults standardUserDefaults] objectForKey:#"txtFieldUserName"]) {
[loadInitialWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.google.com"]]];
}
else {
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#",[self urlEncodeValue:[[NSUserDefaults standardUserDefaults] stringForKey:#"txtFieldUserName"]],[self urlEncodeValue:[[NSUserDefaults standardUserDefaults] stringForKey:#"txtFieldPassWord"]]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://www.mysite.com/page.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[loadInitialWebView loadRequest: request];
}
// End Load WebView
[super viewDidLoad];
}
#end
SecondViewController.h
#import <UIKit/UIKit.h>
NSUserDefaults *prefs;
#interface SecondViewController : UIViewController {
IBOutlet UITextField *txtUserName;
IBOutlet UITextField *txtPassWord;
}
#property (nonatomic, retain) UITextField *txtUserName;
#property (nonatomic, retain) UITextField *txtPassWord;
#property (nonatomic, retain) NSUserDefaults *prefs;
- (IBAction)doneButtonPressed:(id)sender;
#end
SecondViewController.m
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
#implementation SecondViewController
#synthesize txtUserName;
#synthesize txtPassWord;
#synthesize prefs;
// Start Done Button Pressed
- (IBAction)doneButtonPressed:(id)sender;
{
[self dismissModalViewControllerAnimated:YES];
[prefs setObject:txtUserName.text forKey:#"txtFieldUserName"];
[prefs setObject:txtPassWord.text forKey:#"txtFieldPassWord"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
// End Done Button Pressed
// Start Dismiss the keyboard when a user selects the return key
- (BOOL) textFieldShouldReturn: (UITextField *) theTextField
{
[theTextField resignFirstResponder];
return YES;
}
// End Dismiss the keyboard when a user selects the return key
- (void)viewDidLoad
{
self.prefs = [NSUserDefaults standardUserDefaults];
//Start (Code to set a default username,password)
if (![[NSUserDefaults standardUserDefaults] objectForKey:#"txtFieldUserName"]) {
txtUserName.text = #"jdoe1234";
}
else {
txtUserName.text = [[NSUserDefaults standardUserDefaults] stringForKey:#"txtFieldUserName"];
}
if (![[NSUserDefaults standardUserDefaults] objectForKey:#"txtFieldPassWord"]) {
txtPassWord.text = #"01012011";
}
else {
txtPassWord.text = [[NSUserDefaults standardUserDefaults] stringForKey:#"txtFieldPassWord"];
}
// End (Code to set a default username,password)
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
#end
It probably isn't loading into the first page because the view has already been loaded and isn't being reloaded. You would need to add something to your -viewWillAppear in the first view controller to recheck the NSUserDefaults and load them appropriately.