Passing Variables to another View Controller

Discussion in 'iOS Programming' started by mngoose, Oct 3, 2012.

  1. mngoose macrumors member

    Joined:
    May 26, 2012
    #1
    All,
    Hoping to get some help here.

    I have a 4 view app in the following order
    login view
    view with a UITABLE
    detail view
    map view

    What I am trying to do is to pass the variables in the loginview into the Viewcontroller with the UITABLE so that the JSON data can be retrieved from the sql server back in and build the http string the right way to hit the mysql backend.

    here is the code
    appdelegate.h

    Code:
    ppdelegate.h
    
    //
    //  AppDelegate.h
    //  JSONNews
    //
    //  Created by Anthony Frizalone on 7/31/12.
    //  Copyright (c) 2012 Anthony Frizalone. All rights reserved.
    //
    
    #import <UIKit/UIKit.h>
    
    @class ViewController;
    
    @interface AppDelegate : UIResponder <UIApplicationDelegate>
    
    @property (strong, nonatomic) UIWindow *window;
    @property (retain, nonatomic) NSString *username;
    @property (retain, nonatomic) NSString *password;
    
    
    @property (strong, nonatomic) ViewController *viewController;
    @property (strong, nonatomic) ViewController *loginViewController;
    
    
    @end
    
    appdelegate.m
    Code:
    //
    //  AppDelegate.m
    //  JSONNews
    //
    //  Created by Anthony Frizalone on 7/31/12.
    //  Copyright (c) 2012 Anthony Frizalone. All rights reserved.
    //
    
    #import "AppDelegate.h"
    #import "loginViewController.h"
    #import "ViewController.h"
    #import "DetailViewController.h"
    
    @implementation AppDelegate
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        // Override point for customization after application launch.
        self.viewController = [[loginViewController alloc] initWithNibName:@"loginViewController" bundle:nil];
        
        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
        self.window.rootViewController = navController;
        [self.window makeKeyAndVisible];
        
       
        _username = _username;
        _password =_password;
        NSLog(@"%@", _username);
        NSLog(@"%@", _password);
        
        
        
        
        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.
    }
    
    - (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.
    }
    
    - (void)applicationWillTerminate:(UIApplication *)application
    {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    @end
    
    loginViewController.h
    Code:
    //
    //  loginViewController.h
    //  JSONNews
    //
    //  Created by John Schimanski Jr on 9/23/12.
    //  Copyright (c) 2012 Anthony Frizalone. All rights reserved.
    //
    
    #import <UIKit/UIKit.h>
    #import "ViewController.h"
    
    
    
    @interface loginViewController : UIViewController {
    
        IBOutlet UITextField *username;
        IBOutlet UITextField *password;
        IBOutlet UIButton *login;
        
        
    }
    @property (copy, nonatomic) UITextField *username;
    @property (copy, nonatomic) UITextField *password;
    
    
    -(IBAction)login:(id)sender;
    @end
    
    loginviewcontroller.m
    Code:
    //
    //  loginViewController.m
    //  JSONNews
    //
    //  Created by John Schimanski Jr on 9/23/12.
    //  Copyright (c) 2012 Anthony Frizalone. All rights reserved.
    //
    
    #import "loginViewController.h"
    #import "ViewController.h"
    #import "DetailViewController.h"
    #import "AppDelegate.h"
    
    @interface loginViewController ()
    
    @end
    
    @implementation loginViewController
    @synthesize username;
    @synthesize password;
    
    
    -(IBAction)login:(id)sender {
        loginViewController *login = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
        [self presentModalViewController:login animated:YES];
    }
    
    
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self) {
            // Custom initialization
        }
        return self;
    }
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view from its nib.
    }
    
    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    @end
    
    viewcontroller.h
    Code:
    //
    //  ViewController.h
    //  JSONNews
    //
    //  Created by Anthony Frizalone on 7/31/12.
    //  Copyright (c) 2012 Anthony Frizalone. All rights reserved.
    //
    
    #import <UIKit/UIKit.h>
    #import "DetailViewController.h"
    
    @interface ViewController : UIViewController {
        IBOutlet UITableView *mainTableView;
        
        NSArray *news;
        NSMutableData *data;
        NSString *darmed;
        UITextField *password;
        UITextField *username;
        
    }
    @property (strong,nonatomic) NSString *darmed;
    @end
    
    viewcontroller.m
    Code:
    //
    //  ViewController.m
    //  JSONNews
    //
    //  Created by Anthony Frizalone on 7/31/12.
    //  Copyright (c) 2012 Anthony Frizalone. All rights reserved.
    //
    
    #import "ViewController.h"
    #import "DetailViewController.h"
    #import "loginViewController.h"
    
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    
    
    
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        
        username = username.text;
        password = password.text;
        
        NSLog(@"username=%@", username);
        NSLog(@"Password=%@", password);
        self.title = @"Dewalt MobileLock Tracking";
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        
        NSURL *url = [NSURL URLWithString:@"http://10.4.4.11/dewalt/a1.php?Fone=5125551212&pincode=12"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [[NSURLConnection alloc] initWithRequest:request delegate:self];
        
    	// Do any additional setup after loading the view, typically from a nib.
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        data = [[NSMutableData alloc] init];
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
    {
        [data appendData:theData];
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
       
        
        news = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
        [mainTableView reloadData];
    }
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
        UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"The download could not complete - please make sure you're connected to either 3G or Wi-Fi." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
        [errorView show];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    }
    
    - (int)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 1;
    }
    
    - (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return [news count];
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];
        
        
        if(cell == nil){
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MainCell"];
        }
        
        cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:@"dname"];
        
        cell.detailTextLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:@"dlloc"];
        
        NSLog(@"%@", cell);
        
        
        return cell;
    }
    
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        
        DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
        detailViewController.title = [[news objectAtIndex:indexPath.row] objectForKey:@"dname"];
        detailViewController.newsArticle = [news objectAtIndex:indexPath.row];
        [self presentModalViewController:detailViewController animated:YES];
        
        NSLog(@"%@", detailViewController.title);
        NSLog(@"%@", detailViewController.newsArticle);
        
        
        
    }
    
    
    - (void)viewDidUnload
    {
        [super viewDidUnload];
        // Release any retained subviews of the main view.
    }
    
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    }
    
    @end
    
    again I think that this more of a forest for the trees thing I can smell the answer but I can't get a handle on it and the dozen or so tries that I have attempted don't work either.

    Thanks
    RON
     
  2. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #2
    This line from the login: IBAction of your loginViewController is confusing:
    Code:
    loginViewController *login = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    You should rename your login variable.

    These lines, from ViewController's viewDidLoad, are also confusing:
    Code:
    username = username.text;
    password = password.text;
    You're reassigning your UITextFields with NSStrings. Why?

    What are you trying to pass from loginViewController to ViewController?

    P.S. loginViewController looks like a variable name and not a class name. LoginViewController would be better.
     
  3. mngoose thread starter macrumors member

    Joined:
    May 26, 2012
    #3
    Dejo,

    Welcome to my insanity.

    The code from the IBACTION is the push to get to the next view controller that goes out to my json server and gets the data from the back end with a (for now hard coded http string and url pass ) which I eventually what to build on the fly to put the two variables (username and password) into the json string url request from my server in the backend.

    I put the UITEXTFIELDS variables into NSStrings to try and pass them that way by adding the synthesize and the properties to the View Controller.

    AS I said in the other post this is more of a proof of concept and test bench app. We will be renaming / rebuilding it after we get all the intricate problems worked out.
     
  4. nickculbertson macrumors regular

    nickculbertson

    Joined:
    Nov 19, 2010
    Location:
    Nashville, TN
    #4
    What you are looking for is called a singleton class. Google "singleton class xcode" and you will find what you need.

    Nick
     
  5. dejo, Oct 4, 2012
    Last edited: Oct 6, 2012

    dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #5
    Except you're not putting values into NSStrings, but rather into UITextFields, as it were. Those two lines of code should be giving you a compile-time warning; normally it is not a good idea to ignore them.

    Anyways, passing values to a presented view controller is a fairly basic and standard technique. What resources besides this forum are you using to learn about view controller programming?

    Heck, even if you create a skeleton project using the Master-Detail template, you should be able to examine the untouched code and see how Apple is setting the detailViewController's detailItem before presenting the new view.

    I think it's a good idea to take a few seconds to apply good coding standards early on. This may help alleviate confusion when you finally get around to integrating your test code, and especially if somebody else has to. :)

    A singleton is overkill in this case. They're just trying to pass two values to a presented view controller.
     
  6. lasash macrumors member

    Joined:
    Sep 15, 2012
    #6
    What I did when I needed to pass vars from one view to another, is create the var (for example, NSString *linkURL) in the target view controller (for example, ResultsViewController.h) and of course synthesize it.

    Then, import the target view controller (Results View Controller) to the soruce view controller (for example, FormViewController.h) using:

    Code:
    #import ResultsViewController.h
    
    And then, create the ResultsViewController view in the FormViewController.m and pass it the variable:

    Code:
    ResultsViewController *resultsView=[[ResultsViewController alloc] init];
        resultsView.linkURL=[NSString stringWithFormat:@"%@?json=1", currentLink];
    
    You also have lots of YouTube videos which can help.

    Good luck!
     

Share This Page