webview after checking user input - objective-c

I'm a xcode noob, but here's what I'm looking for followed by what I've done. I've created a login and with that login usernameField I'm trying verify the user and open a only a web page specific to that person. The login is working here's all my code
//LoginViewController.h
#import <UIKit/UIKit.h>
#interface LoginViewController : UIViewController
{
IBOutlet UITextField *usernameField;
IBOutlet UITextField *passwordField;
IBOutlet UIButton *loginButton;
IBOutlet UIActivityIndicatorView *loginIndicator;
}
#property(nonatomic, strong) UITextField *usernameField;
#property(nonatomic, strong) UITextField *passwordField;
#property(nonatomic, strong) UIButton *loginButton;
#property(nonatomic, strong) UIActivityIndicatorView *loginIndicator;
-(IBAction) login: (id) sender;
#end
//LoginViewController.m
#import "LoginViewController.h"
#implementation LoginViewController
#synthesize usernameField, passwordField, loginButton, loginIndicator;
-(IBAction) login: (id) sender
{
if ([usernameField.text isEqualToString: #"userOne"] && [passwordField.text
isEqualToString: #"passwordOne"])
{
printf("Success")
//here is where I would like to pass usernameField.text to WebViews
}
else if (([usernameField.text isEqualToString: #"userTwo"] && [passwordField.text
isEqualToString: #"passwordTwo"])
{
printf("Success")
//here is where I would like to pass usernameField.text to WebViews
}
else
{
printf("Login Failed")
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Login Failed"
message:#"Wrong username and password" delegate:self
cancelButtonTitle:#"Done"
otherButtonTitles:nil];
[alert show];
}
loginIndicator.hidden=False;
[loginIndicator startAnimating];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([[segue identifier] isEqualToString:#"fromLogin"])
{
WebViews *wvc = [segue destinationViewController];
wvc.usernamerField = self.usernameField.text;
}
}
#end
//WebViews.h
#interface WebViews : UIViewController
{
IBOutlet UIWebView *webView;
NSString *usernameField;
}
#property (nonatomic, strong) NSString*usernameField;
#end
//WebViews.m
#import "WebViews.h"
#interface WebViews ()//To be honest I'm not sure what this is for
#end
#implementation WebViews
#synthesize usernameField;
-(void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"username is = %#", self.usernameField);
if([T.usernameField.text isEqualToString: #"userOne"])
{
[webView loadRequest: [NSURLRequest requestWithURL: [NSURL
URLWithString:#"http://www.google.com"]]];
}
else if([T.usernameField.text isEqualToString: #"userTwo"])
{
[webView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString:#"http://www.yahoo.com"]]];
}
else
{
[webView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString:#"http://www.wikipedia.com"]]];
}
#end
Any help is greatly appreciated

Your problem is that you are never assigning anything to T so it is nil in your method.
In the code for your LoginViewController you need to pass the username to the WebViewController. You can do this by implementing the prepareForSegue method.
Here is an example, taken from How to pass prepareForSegue: an object
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure your segue name in storyboard is the same as this line
if ([[segue identifier] isEqualToString:#"YOUR_SEGUE_NAME_HERE"])
{
// Get reference to the destination view controller
WebViewController *wvc = [segue destinationViewController];
// Pass any objects to the view controller here, like...
wvc.username = self.usernameField.text;
}
}

Related

Objective-c: passing data from UITable to ViewController with prepareForSegue

this is my very first app and, basically, this part consists in passing data from a UItableView to a second View Controll. I managed to learn how to pass data from a simple NSarray (also in a UITable), but my goal is to pass values from a NSDictionary. Everything is set up, but I can't figure out how to write the PrepareForSegue method properly. The app runs, but the label on the "DetailView" stays empty. What I got so far:
#implementation TableViewController
- (void)viewDidLoad {
[super viewDidLoad];
_citySpots = #{#"Bars" : #[#"Hurricane", #"Black Swan", #"Texas"],
#"Clubs" : #[#"Electric Wizard", #"Offspring", #"The Tunnel"],
#"Restaurants" : #[#"Nando's", #"1/2 Burguer", #"Satellite"],
};
_sectionTitles = [[_citySpots allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
}
PrepareForSegue Method:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"spotsDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
DetailViewController *destViewController = segue.destinationViewController;
NSString *sectionTitle = [_sectionTitles objectAtIndex:indexPath.section];
NSArray *citySpots = [_citySpots objectForKey:sectionTitle];
destViewController.receiver = [citySpots objectAtIndex:indexPath.row];
}
}
And the receiver(header):
#import <UIKit/UIKit.h>
#import "TableViewController.h"
#interface DetailViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *receiver;
#property (nonatomic, strong) NSString *spot;
#end
Main:
#import "DetailViewController.h"
#interface DetailViewController ()
#end
#implementation DetailViewController
- (void)viewDidLoad {
[super viewDidLoad];
_receiver.text =_spot;
}
Can someone help me out? Thanks
Try to use setters:
[destViewController setReceiver:[citySpots objectAtIndex:indexPath.row]];
[destViewController setSpot:[citySpots objectAtIndex:indexPath.row]];

Incomplete implementations

I'm working on a project in Xcode and getting an error from didReceiveMemoryWarning and incomplete implementation. This is the main file:
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#interface LoginViewController : UIViewController
#property (strong, nonatomic) IBOutlet UIScrollView *scroller;
#property (weak, nonatomic) IBOutlet UITextField *FirstNameField;
#property (weak, nonatomic) IBOutlet UITextField *SurnameField;
#property (weak, nonatomic) IBOutlet UITextField *EmailField;
#property (weak, nonatomic) IBOutlet UITextField *PasswordField;
#property (weak, nonatomic) IBOutlet UITextField *ReenterPasswordField;
- (IBAction)RegisterAction:(id)sender;
#end
This is .m file:
#import "LoginViewController.h"
#interface LoginViewController ()
#end
#implementation LoginViewController
#synthesize scroller;
- (void)viewDidLoad
{
[super viewDidLoad];
[scroller setScrollEnabled:YES];
[scroller setContentSize:CGSizeMake(340, 600)];
}
- (void)viewDidAppear:(BOOL)animated
{
PFUser *user = [PFUser currentUser];
if (user.email != nil) {
[self performSegueWithIdentifier:#"login" sender:self];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)RegisterAction:(id)sender {
[_FirstNameField resignFirstResponder];
[_SurnameField resignFirstResponder];
[_EmailField resignFirstResponder];
[_PasswordField resignFirstResponder];
[_ReenterPasswordField resignFirstResponder];
[self checkFieldsComplete];
[self checkFieldsComplete];
}
- (void) checkFieldsComplete {
if ([_FirstNameField.text isEqualToString:#""] || [_SurnameField.text isEqualToString:#""]|| [_EmailField.text isEqualToString:#""] || [_PasswordField.text isEqualToString:#""] || [_ReenterPasswordField.text isEqualToString:#""]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oops" message: #"Make sure to complete every field" delegate: nil cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[alert show];
} else {
[self checkPasswordsMatch];
}
}
- (void) checkPasswordsMatch {
if (![_PasswordField.text isEqualToString:_ReenterPasswordField.text]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oops" message: #"Passwords don't match" delegate: nil cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[alert show];
}
}
- (void) registerNewUser {
PFUser *newUser;
newUser.username = [NSString stringWithFormat: _FirstNameField.text, _SurnameField.text];
newUser.email = _EmailField.text;
newUser.password = _PasswordField.text;
[newUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
NSLog(#"Welcome to Vici!");
[self performSegueWithIdentifier:#"login"
sender:self];
} else {
NSLog(#"There was an error in registration");
}
}];
}
#end
Can anyone point out a solution?
You are missing a closing brace at viewDidAppear, and thus it's getting confused by the rest of the #implementation and complaining because it's not finding RegisterAction as a result. It's showing you the warning at didReceiveMemoryWarning because that was the first bit of code after your missing brace (which shows you how to find the issue in the future).
Add the missing brace and you should get past this error.

segue data passing returns nil

I need to pass a NSString to my other ViewController but it keeps returning nil.
//prepareForSegue is called from didSelectRowAtIndexPath
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([[segue identifier] isEqualToString:#"chat"]) {
NSString *userName = (NSString *) [toUsersArray objectAtIndex:[self.chatsTableView indexPathForSelectedRow].row];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
ChatViewController *chatViewController = [storyboard instantiateViewControllerWithIdentifier:#"ChatViewController"];
//[chatViewController setChatWithUser:userName]; EVEN TRIED:
chatViewController.chatWithUser = username;
}
}
Here is where I declare the NSString:
#interface ChatViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, MessageDelegate> {
UITextField *messageField;
NSString *chatWithUser;
UITableView *chatTableView;
NSMutableArray *messagesArray;
}
#property (nonatomic,retain) IBOutlet UITextField *messageField;
#property (nonatomic,retain) NSString *chatWithUser;
#property (nonatomic,retain) IBOutlet UITableView *chatTableView;
- (IBAction) sendMessage;
#end
and here its still nil:
#synthesize chatWithUser;
- (void)viewDidLoad {
[super viewDidLoad];
//DO STUFF WITH chatWithUser; ADDED BREAKPOINT AND chatWithUser = nil;
//ALSO TRIED viewWillAppear;
}
What is the right way to pass data between these two View Controllers? My variables stay nil.
The problem is that you're instantiating a new ChatViewController, that's not the one that the segue is going to. You should get that controller from the segue's destinationViewController property.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([[segue identifier] isEqualToString:#"chat"]) {
NSString *userName = (NSString *) [toUsersArray objectAtIndex:[self.chatsTableView indexPathForSelectedRow].row];
ChatViewController *chatViewController = segue.destinationViewController;
chatViewController.chatWithUser = username;
}
}
// Get reference to the destination view controller
ChatViewController *ChatViewController = [segue destinationViewController];

Passing data in NSString format from LoginViewController to FirstViewController

LoginViewController is my initial view controller. Email address is an input in the LoginViewController and I am trying to send it to FirstViewController. I went through a lot of solutions posted here but was unsuccessful to find a link to my answer.
Please have a look at my code and tell me where I am going wrong. I am stuck at this point from a couple of days. My main problem is that, the output of emailString shows null when I print it to see if it was carried to the FirstViewController.
FYI - I am using storyboard. I have a Tab Bar Controller which has three tabs and FirstViewController is the first tab page.
LoginViewController.h
#import <UIKit/UIKit.h>
#import "FirstViewController.h"
#interface LoginViewController : UIViewController{
NSString *email;
}
- (IBAction)LoginButton:(id)sender;
- (IBAction)CancelButton:(id)sender;
- (IBAction)dismissKeyboard:(id)sender;
#property (weak, nonatomic) IBOutlet UITextField *EmailField;
#property (weak, nonatomic) IBOutlet UITextField *PasswordField;
#end
LoginViewController.m
#import "LoginViewController.h"
#import "FirstViewController.h"
#define USERNAME #"abc#gmail.com"
#interface LoginViewController ()
#end
#implementation LoginViewController
#synthesize EmailField;
#synthesize PasswordField;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
email = [[NSString alloc] init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)LoginButton:(id)sender {
email = EmailField.text;
if([EmailField.text isEqualToString:USERNAME])
{
FirstViewController *fvc = [[FirstViewController alloc]initWithNibName:#"FirstViewController" bundle:nil];
fvc.emailString = [[NSString alloc] initWithFormat:#"%#",EmailField.text];
// fvc.emailString = email;
[self.navigationController pushViewController:fvc animated:YES];
}
[EmailField resignFirstResponder];
}
- (IBAction)CancelButton:(id)sender {
NSLog(#"Cancel button pressed!!!");
[EmailField resignFirstResponder];
[PasswordField resignFirstResponder];
}
- (IBAction)dismissKeyboard:(id)sender {
[EmailField resignFirstResponder];
[PasswordField resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[self LoginButton:nil];
[textField resignFirstResponder];
return YES;
}
#end
FirstViewController.h
#import <UIKit/UIKit.h>
#import "LoginViewController.h"
#interface FirstViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *emailLabel;
#property (nonatomic, retain) NSMutableData *receivedData;
#property (copy) NSString *emailString;
FirstViewController.m
#import "FirstViewController.h"
#interface FirstViewController ()
#end
#implementation FirstViewController
#synthesize emailLabel;
#synthesize receivedData;
#synthesize emailString;
- (void)viewDidLoad
{
[super viewDidLoad];
[emailLabel setText: emailString];
NSString *theURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://.....email=%#",emailString]];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:theURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if(connection){
NSLog(#"connection successful");
NSLog(#"%#",emailString);
receivedData = [NSMutableData data];
}
else{
NSLog(#"connection failed");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[receivedData setLength:0];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(#"Success");
NSLog(#"Received %d bytes of data",[receivedData length]);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
I tried implementing prepareFOrSegue method in LoginViewController too. But it still didnot make any change. This is the code I have written in it.
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:#"showDetailSegue"])
{
NSString *email = EmailField.text;
NSLog (#"++++++++++ %#", email);
FirstViewController *fvc = [segue destinationViewController];
fvc.emailString=email;
}
}
Screenshot of Storyboard:
If you are using StoryBoards I'd strongly suggest you use segues to call the different view controllers. That way you can push vc's and pass info relatively easily.
You can override the native method prepareForSegue in your Login VC, and set the properties there. You can name your segue id as anything in the storyboard.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"firstVC"]) {
FirstViewController *firstVC = [segue destinationViewController];
firstVC.emailString = EmailField.text;
}
}
if you really want, and I'd advise against it vs. using static variables is
NSUserDefaults.
[[NSUserDefaults standardUserDefaults]
setObject:EmailField.text forKey:#"emailString"];
to get it back later
NSString *emailString = [[NSUserDefaults standardUserDefaults]
stringForKey:#"emailString"];
NSLog(#"%#",emailString);
I would save the Email and password in the IOS Keychain securely instead of passing it in between views.
https://developer.apple.com/library/ios/#documentation/security/conceptual/keychainServConcepts/iPhoneTasks/iPhoneTasks.html#//apple_ref/doc/uid/TP30000897-CH208-SW1
I got the solution.
The only three lines requires for me to add in the prepareForSegue were these three and I got my program working
FirstViewController* fvc = [[FirstViewController alloc] init];
UITabBarController *tbc = [segue destinationViewController];
fvc = (FirstViewController *) [[tbc customizableViewControllers] objectAtIndex:0];
Thanks everyone!

delegate gets null when performWithSegue

Im trying to send some info from a modal view to a delgate. But it seems like my delegate doesnt follow through, it gets null. It looks like this in IB http://i.imgur.com/7oaxb.png.
But it works if i remove the navigationController that is right before the modal view and use the buttons in the View.
please help, ive tried for like 5 hours... :/
Heres the modalViewController code:
#import
#import "Link.h"
#protocol modalViewDelegate <NSObject>
-(void)closeview;
-(void)saveLink:(Link *)link;
#end
#interface modelViewController : UIViewController
#property (weak, nonatomic) IBOutlet UITextField *titel;
#property (weak, nonatomic) IBOutlet UITextField *url;
#property (nonatomic, weak) id <modalViewDelegate> delegate;
- (IBAction)exitModal:(id)sender;
- (IBAction)saveLink:(id)sender;
#end
and .m:
#import "modelViewController.h"
#interface modelViewController ()
#end
#implementation modelViewController
#synthesize titel;
#synthesize url, delegate;
- (IBAction)exitModal:(id)sender {
//[self.delegate closeview];
[self dismissModalViewControllerAnimated:YES];
}
- (IBAction)saveLink:(id)sender {
if (titel.text.length > 0 && url.text.length > 0) {
NSString *urlen = [NSString stringWithFormat:#"%#", url.text];
Link *linken = [[Link alloc] initWithURL:[NSURL URLWithString:urlen]];
linken.title = titel.text;
NSLog(#"%#", delegate); **//returns null when pressing button** it returns null if i put it in viewDidLoad to..
[self.delegate saveLink:linken];
[self dismissModalViewControllerAnimated:YES];
} else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:#"warning" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alertView show];
}
}
#end
the MasterViewController .h (that pushes the modalview:
#import <UIKit/UIKit.h>
#import "modelViewController.h"
#class DetailViewController;
#interface MasterViewController : UITableViewController <modalViewDelegate>
....
and .m
#import "MasterViewController.h"
#import "DetailViewController.h"
#implementation MasterViewController
#synthesize detailViewController = _detailViewController;
#synthesize links;
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"linkPush"]) {
// Skicka länken till detaljvyn
DetailViewController *detailVC = segue.destinationViewController;
detailVC.link = [self.links objectAtIndex:self.tableView.indexPathForSelectedRow.row];
NSLog(#"%#", detailVC);
}
//this is the modalview "pusher"
if ([segue.identifier isEqualToString:#"newLink"]) {
modelViewController *mvc = segue.destinationViewController;
mvc.delegate = self;
NSLog(#"%#", mvc.delegate);
}
}
- (void)closeview {
[self dismissModalViewControllerAnimated:YES];
//[self.tabBarController dismissModalViewControllerAnimated:YES];
}
-(void)saveLink:(Link *)link{
NSLog(#"hello");
[links insertObject:link atIndex:links.count]; //updates a Tableview and works fine if delegate is called
[self.tableView reloadData];
//[self dismissModalViewControllerAnimated:YES];
}
If your destination view controller is wrapped into a navigation controller, you have to refer to it differently in prepareForSegue:
UINavigationController *nav = segue.destinationViewController;
DetailViewController *dvc = [nav.viewControllers objectAtIndex:0];
Now setting the properties, including the delegate, should work.