代码随着传递数据而不断崩溃

时间:2014-10-11 11:23:53

标签: ios objective-c

我正在使用登录系统构建我的第一个iOS应用程序。我之前已经构建了一些简单的东西,但这是一个全新的水平。目前我能够登录并从服务器获取一些数据。然后,该应用会附加model segueMainView并附加MainController

当我登录时,应用从服务器返回tokensuccess。进一步请求服务器需要此令牌。但是,我似乎无法弄清楚如何将令牌传递给MainController。无论我尝试什么,应用程序都会因未知错误而崩溃。

现在 - 使用下面的代码 - 它会抛出:

2014-10-11 14:30:14.077 LoginScreen[29076:4688502] -[UINavigationController setXAuthToken:]: unrecognized selector sent to instance 0x7bfd1140 2014-10-11 14:30:14.104 LoginScreen[29076:4688502] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UINavigationController setXAuthToken:]: unrecognized selector sent to instance 0x7bfd1140'

ViewController.h

#import <UIKit/UIKit.h>
#import "MainController.h"

@interface ViewController : UIViewController <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *txtUsername;
@property (weak, nonatomic) IBOutlet UITextField *txtPassword;

- (IBAction)sigininClicked:(id)sender;

- (IBAction)backgroundTap:(id)sender;
@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)sigininClicked:(id)sender {
    NSInteger success = 0;
    @try {

        if([[self.txtUsername text] isEqualToString:@""] || [[self.txtPassword text] isEqualToString:@""] ) {

            [self alertStatus:@"Please enter Email and Password" :@"Sign in Failed!" :0];

        } else {
            NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[self.txtUsername text],[self.txtPassword text]];
            NSLog(@"PostData: %@",post);

            NSURL *url=[NSURL URLWithString:@"http://www.mywebsite.com/auth"];

            NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

            NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setURL:url];
            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:postData];

            //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

            NSError *error = [[NSError alloc] init];
            NSHTTPURLResponse *response = nil;
            NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

            NSLog(@"Response code: %ld", (long)[response statusCode]);

            if ([response statusCode] >= 200 && [response statusCode] < 300)
            {
                NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
                NSLog(@"Response ==> %@", responseData);

                NSError *error = nil;
                NSDictionary *jsonData = [NSJSONSerialization
                                          JSONObjectWithData:urlData
                                          options:NSJSONReadingMutableContainers
                                          error:&error];

                success = [jsonData[@"success"] integerValue];
                NSLog(@"Success: %ld",(long)success);

                if(success == 1)
                {
                    NSLog(@"Login SUCCESS");
                } else {

                    NSString *error_msg = (NSString *) jsonData[@"error_message"];
                    [self alertStatus:error_msg :@"Sign in Failed!" :0];
                }

            } else {
                //if (error) NSLog(@"Error: %@", error);
                [self alertStatus:@"Connection Failed" :@"Sign in Failed!" :0];
            }
        }
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
        [self alertStatus:@"Sign in Failed." :@"Error!" :0];
    }
    if (success) {

        [self performSegueWithIdentifier:@"login_success" sender:self];
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"login_success"]) {
        MainController *controller = (MainController *)segue.destinationViewController;
        controller.xAuthToken = @"test string";
    }
}

- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];
    alertView.tag = tag;
    [alertView show];
}

- (IBAction)backgroundTap:(id)sender {
    [self.view endEditing:YES];
}

-(BOOL) textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

@end

MainController.h

#import <Foundation/Foundation.h>

@interface MainController : UIViewController

@property (nonatomic,strong) NSString *xAuthToken;

@end

MainController.m

#import "MainController.h"

@interface MainController ()

@end

@implementation MainController

- (void)viewDidLoad
{
    NSLog(@"%@",_xAuthToken);
}

@end

1 个答案:

答案 0 :(得分:0)

堆栈跟踪告诉您问题是什么 - 您正在尝试在UINavigationController上设置XAuthToken属性 - 但是UINavigationController没有该属性。

您的MainController实例嵌入在UINavigationController中,因此您可以从destinationViewController prepareForSegue获取该实例。

您需要访问视图控制器堆栈 -

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"login_success"]) {
        UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
        MainController *controller = (MainController *)navController.topViewController
        controller.xAuthToken = @"test string";
    }
}