为什么当我删除 UIAlertView 时,pushViewController 停止工作

发布于 2024-12-11 07:58:05 字数 19098 浏览 0 评论 0原文

我外包了一些 iPhone 开发,我试图对代码进行简单的更改,但这对我来说没有任何意义。我希望有人能帮助我。我想问原来的开发商,但他们刚刚休假一周,我宁愿不等。

//
//  SettingViewController.m
//  FoodStorageManagement
//
//  Created by Ryan McLaughlin on 10/20/11.
//  Copyright 2011 Food Storage Management. All rights reserved.
//

#import "SettingViewController.h"
#import "MainViewController.h"
#import "XMLRPCRequest.h"
#import "XMLRPCResponse.h"
#import "XMLRPCConnection.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
@implementation SettingViewController
@synthesize Obj_string,LoginState,hashkey,validuser,apikey,spinnerView; 

-(id)init
{
    [super init];
    img_loginBg=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Loginpage.png"]];
    img_loginBg.frame=CGRectMake(0, 0, 320, 460);

    app=[[UIApplication sharedApplication]delegate];

    UserIDtxt=[[UITextField alloc]initWithFrame:CGRectMake(150, 163, 160, 25)];
    UserIDtxt.returnKeyType=UIReturnKeyDone;
    UserIDtxt.backgroundColor=[UIColor clearColor];
    //UserIDtxt.text=@"user";
    UserIDtxt.delegate=self;
    UserIDtxt.tag=1;

    pwdText=[[UITextField alloc]initWithFrame:CGRectMake(150, 220, 160, 25)];
    pwdText.backgroundColor=[UIColor clearColor];
    //pwdText.text=@"123456";
    pwdText.secureTextEntry=YES;
    pwdText.returnKeyType=UIReturnKeyDone;
    pwdText.delegate=self;
    pwdText.tag=2;

    btn_SignUp=[UIButton buttonWithType:UIButtonTypeCustom];
    btn_SignUp.frame=CGRectMake(45, 335, 95, 35);
    btn_SignUp.backgroundColor=[UIColor clearColor];
    [btn_SignUp setTitle:@"" forState:UIControlStateNormal];
    [btn_SignUp addTarget:self action:@selector(ClickOnSignUp) forControlEvents:UIControlEventTouchUpInside];
    [btn_SignUp retain];

    btn_LogIn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn_LogIn.frame=CGRectMake(175, 335, 95, 35);
    btn_LogIn.backgroundColor=[UIColor clearColor];
    [btn_LogIn setTitle:@"" forState:UIControlStateNormal];
    [btn_LogIn addTarget:self action:@selector(ClickOnLogIn) forControlEvents:UIControlEventTouchUpInside];
    [btn_LogIn retain];

    NSString *deviceVersion=[UIDevice currentDevice].systemVersion;
    NSLog(@"%@",deviceVersion);

    btn_Back=[UIButton buttonWithType:UIButtonTypeCustom];
    btn_Back.frame=CGRectMake(8, 417, 50, 40);
    btn_Back.backgroundColor=[UIColor clearColor];
    [btn_Back setTitle:@"" forState:UIControlStateNormal];
    [btn_Back addTarget:self action:@selector(ClickOnBack) forControlEvents:UIControlEventTouchUpInside];
    [btn_Back retain];

    return self;
}

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView 
{
    [super loadView];
    [self.view addSubview:img_loginBg];
    [self.view addSubview:btn_SignUp];
    [self.view addSubview:btn_LogIn];
    [self.view addSubview:btn_Back];
    [self.view addSubview:UserIDtxt];
    [self.view addSubview:pwdText];
}

-(void)ClickOnSignUp
{
    Connection=[[NetworkConnection alloc]initConnection];
    if (Connection.isReachable)
    {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.foodstoragemanagement.com/signup.php"]];
    }
    else 
    {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Inventory" message:@"Network Connection unavailable.."  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginError show];
        [LoginError release];

    }
}

-(void) startSpinner:(NSString*)type andDisplay:(NSString*)display{

    //remove any existing spinners at this point

    if(self.spinnerView)
    {
        [self.spinnerView.view removeFromSuperview];
        self.spinnerView = nil;
    }
    self.spinnerView =[[[SpinnerModal alloc]initWithType:type andDisplay:display]autorelease];
    //add this to the root view of the app
    //ViewManager *viewMgr = [ViewManager getManager];
    [self.view addSubview:self.spinnerView.view];   
}

-(void) stopSpinner{
    NSLog(@"SPINNER IS REMOVED");
    [self.spinnerView.view removeFromSuperview];
    self.spinnerView = nil;
}

-(void)ClickOnLogIn
{
    Connection=[[NetworkConnection alloc]initConnection];
    if (Connection.isReachable)
    {
        [self startSpinner:@"spinner" andDisplay:@"Loading"];
        timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(ClickOnLog) userInfo:nil repeats:NO];
    }
    else {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Inventory" message:@"Network Connection unavailable.."  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [LoginError show];
                [LoginError release];
        [self stopSpinner];
    }

}

-(void)ClickOnLog
{
    NSDate* now = [NSDate date];
    NSString *dateString=[[NSString alloc]init];
    dateString = [now description];
    dateString=[self dateInFormat:@"%s"];

    NSString *username=[UserIDtxt.text lowercaseString];
    NSString *username_reverse=[username reverseString];

    NSString *password_hash=[self sha256:pwdText.text];

    NSString *str=[NSString stringWithFormat:@"%@%@%@",username,password_hash,dateString];
    str=[self sha256:str];
    app.username=[NSMutableString stringWithString:username];
    app.password=[NSMutableString stringWithString:password_hash];

    //url from plist
    NSString *server=[[NSString alloc]init];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
    NSMutableDictionary *plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    server=[plistDict objectForKey:@"NewUrl"];

    XMLRPCRequest *reqHello = [[XMLRPCRequest alloc] initWithHost:[NSURL URLWithString:server]];
    NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];

    [dict setValue:[UserIDtxt.text lowercaseString] forKey:@"username"];
    [dict setValue:str forKey:@"hash_key"];
    [dict setValue:dateString forKey:@"timestamp"];


    [reqHello setMethod:@"user.get_api" withObjects:[NSArray arrayWithObjects:dict,nil]];

    NSString *result=[self executeXMLRPCRequest:reqHello];
    if ([result length]>0)
    {   
        NSLog(@"OUTPUT %@",result);
        NSData* data=[result dataUsingEncoding:NSUTF8StringEncoding];
        NSXMLParser *parser1=[[NSXMLParser alloc]initWithData:data];
        [parser1 setDelegate:self];
        [parser1 parse];
        [reqHello release];

        defaults = [NSUserDefaults standardUserDefaults];
        app.defaultuser=[NSUserDefaults standardUserDefaults];
        [defaults setObject: app.globalApi_key forKey: @"api_key"];
        [defaults setObject:UserIDtxt.text forKey:@"username"];
        [defaults setObject:pwdText.text forKey:@"password"];
        app.defaultuser=defaults;   

        if (!app.globalApi_key)
        {
            defaults = [NSUserDefaults standardUserDefaults];
        }
        [defaults synchronize];
        if (!val)
        {
            val=[defaults objectForKey:@"api_key"];
        }

    }
    else 
    {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Inventory" message:@"Unable to communicate with the server"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginError show];
        [LoginError release];
    }

    if( ![result isKindOfClass:[NSString class]] )//error occured
    {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Inventory" message:@"unable to communicate with server"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginError show];
        [LoginError release];
    }
    else 
    {
        if ([self.validuser isEqualToString:@"Authenticated Successfully"])
        {
            if (app.Authorisation==TRUE) 
            {
                UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:@"Authentication" message:@"Authenticated successfully!!!"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [LoginOK show];
                [LoginOK release];
            }   
            else 
            {
                MainViewController *main=[[MainViewController alloc]init];
                [self.navigationController pushViewController:main animated:YES];
                [main release];

            }
        }
        else 
        {
            UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Authentication" message:self.validuser  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [LoginError show];
            [LoginError release];
        }
    } 
    [self stopSpinner];
}

- (void)alertView:(UIAlertView *)ConfirmationAlert didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if([ConfirmationAlert.title isEqualToString:@"Authentication"])

    {
        [self dismissModalViewControllerAnimated:YES];
        app.Authorisation=FALSE;
    }
}

# pragma mark Parsing Delegate Methods
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
    if([elementName isEqualToString:@"params"])
    {
        Obj_string = [[NSMutableString alloc]init];
        LoginState =[[NSMutableString alloc]init];
        hashkey=[[NSMutableString alloc]init];
        validuser=[[NSMutableString alloc]init];

    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if([elementName isEqualToString:@"name"])
    {
        self.LoginState=self.Obj_string;
    }
    else if([elementName isEqualToString:@"string"])
    {
        //NSLog(@"%@",Obj_string);
        if([self.LoginState isEqualToString:@"hash_key"])
        {
            self.hashkey=self.Obj_string;
            app.globalhash_key=self.hashkey;
        }
        if([self.LoginState isEqualToString:@"api"])
        {
            self.apikey=self.Obj_string;
            app.globalApi_key=self.apikey;
        }
        if([self.LoginState isEqualToString:@"message"])
        {
            self.validuser=self.Obj_string;
        }
    }

    [Obj_string release];
    Obj_string = nil;
    Obj_string = [[NSMutableString alloc]init];
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    [Obj_string appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
    //[LoginState appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];

}


-(NSString *)dateInFormat:(NSString*)stringFormat {
    char buffer[80];
    const char *format = [stringFormat UTF8String];
    time_t rawtime;
    struct tm * timeinfo;
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    strftime(buffer, 80, format, timeinfo);
    return [NSString  stringWithCString:buffer encoding:NSUTF8StringEncoding];
}

- (NSString *)sha256:(NSString *)str
{   
    const char *inputString = [str UTF8String];
    unsigned char hashedChars[32]; // 32bit encoding
    //unsigned char hashedChars[64]; // 64 bit encoding
    //unsigned char hashedChars[64]; //16 bit encoding
    CC_SHA256(inputString , strlen(inputString), hashedChars);
    NSData *hashedData = [NSData dataWithBytes:hashedChars length:32];//32bit encoding
    //NSData *hashedData = [NSData dataWithBytes:hashedChars length:64]; //64bit encoding
    //NSData *hashedData = [NSData dataWithBytes:hashedChars length:16]; //16bit encoding

    NSLog(@"hashedData = %@", hashedData);
    NSString *someString = [NSString stringWithFormat:@"%@", hashedData];

    someString = [someString stringByReplacingOccurrencesOfString:@" " withString:@""];
    someString = [someString stringByReplacingOccurrencesOfString:@"<" withString:@""];
    someString = [someString stringByReplacingOccurrencesOfString:@">" withString:@""];
    //return hash;
    return someString;
}

- (NSString *)getMD5FromString:(NSString *)source
{
    const char *src = [source UTF8String];
    unsigned char result[16];
    CC_MD5(src, strlen(src), result);
    NSString *ret = [[[NSString alloc] initWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                      result[0], result[1], result[2], result[3],
                      result[4], result[5], result[6], result[7],
                      result[8], result[9], result[10], result[11],
                      result[12], result[13], result[14], result[15]
                      ] autorelease];
    return [ret lowercaseString];
}

- (id)executeXMLRPCRequest:(XMLRPCRequest *)req
{
    XMLRPCResponse *userInfoResponse = [XMLRPCConnection sendSynchronousXMLRPCRequest:req];
    return [userInfoResponse object];
}

-(void)ClickOnBack
{
    [self dismissModalViewControllerAnimated:YES];
    //[self.navigationController popViewControllerAnimated:YES];
    //MainViewController *mainView=[[MainViewController alloc]init];
//  [self.navigationController popToViewController:mainView animated:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
    NSInteger nextTag = textField.tag + 1;
    // Try to find next responder
    UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
    if (nextResponder) {
        // Found next responder, so set it.
        [nextResponder becomeFirstResponder];
    } else {
        // Not found, so remove keyboard.
        [textField resignFirstResponder];
    }
    return NO; // We do not want UITextField to insert line-breaks.
}

-(NSString*) digest:(NSString*)input  
{  

    NSData *data = [input dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
  //  uint8_t digest[CC_SHA1_DIGEST_LENGTH];  
    uint8_t digest[CC_SHA256_DIGEST_LENGTH];  

    CC_SHA1(data.bytes, data.length, digest);  
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];  

   // for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)  

        for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)  

        [output appendFormat:@"%02x", digest[i]];  

    return output;  

}  


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

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

有问题的部分是这个

if ([self.validuser isEqualToString:@"Authenticated Successfully"])
    {
        if (app.Authorisation==TRUE) 
        {
            UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:@"Authentication" message:@"Authenticated successfully!!!"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [LoginOK show];
            [LoginOK release];
        }   
        else 
        {
            MainViewController *main=[[MainViewController alloc]init];
            [self.navigationController pushViewController:main animated:YES];
            [main release];

        }
    }
    else 
    {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Authentication" message:self.validuser  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginError show];
        [LoginError release];
    }
} 

表面上看起来很简单。我想要做的更改是删除此警报

UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:@"Authentication" message:@"Authenticated successfully!!!"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [LoginOK show];
                [LoginOK release];

但是,对警报的任何更改都会导致 PushViewController 停止工作。我已经尝试注释掉警报,

if ([self.validuser isEqualToString:@"Authenticated Successfully"])
    {
    if (app.Authorisation==TRUE) 
    {
       // UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:@"Authentication" message:@"Authenticated successfully!!!"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        //[LoginOK show];
        //[LoginOK release];
    }   
    else 
    {
        MainViewController *main=[[MainViewController alloc]init];
        [self.navigationController pushViewController:main animated:YES];
        [main release];

    }
    }
    else 
    {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Authentication" message:self.validuser  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginError show];
        [LoginError release];
    }
} 

我已经尝试重写第二个如果

if ([self.validuser isEqualToString:@"Authenticated Successfully"])
    {
    if (app.Authorisation==FALSE) 
    {

        MainViewController *main=[[MainViewController alloc]init];
        [self.navigationController pushViewController:main animated:YES];
        [main release];

    }
    }
    else 
    {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Authentication" message:self.validuser  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginError show];
        [LoginError release];
    }
} 

我也尝试完全删除第二个如果

if ([self.validuser isEqualToString:@"Authenticated Successfully"])
    {

        MainViewController *main=[[MainViewController alloc]init];
        [self.navigationController pushViewController:main animated:YES];
        [main release];


    }
    else 
    {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Authentication" message:self.validuser  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginError show];
        [LoginError release];
    }
} 

但是pushViewController将无法工作,除非我在代码中有警报。我没有收到任何错误,应用程序也没有崩溃,它只是停留在当前页面,所以我完全不知所措。这让我认为他们的某些操作是通过单击警报中的“确定”来触发的,但我在代码中没有看到任何内容。

我还单步执行了代码,看看是否能发现问题,但看起来不错。

如果重要的话,我正在使用 xcode 4.2 和 iOS 5 sdk。

另一个奇怪的现象是,如果我运行这样的代码

if ([self.validuser isEqualToString:@"Authenticated Successfully"])
        {

                MainViewController *main=[[MainViewController alloc]init];
                [self.navigationController pushViewController:main animated:YES];
                [main release];

        }
        else 
        {
            UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Authentication" message:self.validuser  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [LoginError show];
            [LoginError release];
        }

,我会收到登录错误(意味着它会触发 else 中的警报)。然后单击“确定”后,它将进入下一页。我真的不明白这是怎么发生的,因为它们位于 if 的不同部分。我一定错过了一些明显的东西。

I outsourced some iPhone development and I am trying to make a simple change to the code, but it does not make any sense to me. I am hoping that someone can help me out. I would ask the original developer, but they just left for a week long vacation and I would prefer to not wait.

//
//  SettingViewController.m
//  FoodStorageManagement
//
//  Created by Ryan McLaughlin on 10/20/11.
//  Copyright 2011 Food Storage Management. All rights reserved.
//

#import "SettingViewController.h"
#import "MainViewController.h"
#import "XMLRPCRequest.h"
#import "XMLRPCResponse.h"
#import "XMLRPCConnection.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
@implementation SettingViewController
@synthesize Obj_string,LoginState,hashkey,validuser,apikey,spinnerView; 

-(id)init
{
    [super init];
    img_loginBg=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Loginpage.png"]];
    img_loginBg.frame=CGRectMake(0, 0, 320, 460);

    app=[[UIApplication sharedApplication]delegate];

    UserIDtxt=[[UITextField alloc]initWithFrame:CGRectMake(150, 163, 160, 25)];
    UserIDtxt.returnKeyType=UIReturnKeyDone;
    UserIDtxt.backgroundColor=[UIColor clearColor];
    //UserIDtxt.text=@"user";
    UserIDtxt.delegate=self;
    UserIDtxt.tag=1;

    pwdText=[[UITextField alloc]initWithFrame:CGRectMake(150, 220, 160, 25)];
    pwdText.backgroundColor=[UIColor clearColor];
    //pwdText.text=@"123456";
    pwdText.secureTextEntry=YES;
    pwdText.returnKeyType=UIReturnKeyDone;
    pwdText.delegate=self;
    pwdText.tag=2;

    btn_SignUp=[UIButton buttonWithType:UIButtonTypeCustom];
    btn_SignUp.frame=CGRectMake(45, 335, 95, 35);
    btn_SignUp.backgroundColor=[UIColor clearColor];
    [btn_SignUp setTitle:@"" forState:UIControlStateNormal];
    [btn_SignUp addTarget:self action:@selector(ClickOnSignUp) forControlEvents:UIControlEventTouchUpInside];
    [btn_SignUp retain];

    btn_LogIn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn_LogIn.frame=CGRectMake(175, 335, 95, 35);
    btn_LogIn.backgroundColor=[UIColor clearColor];
    [btn_LogIn setTitle:@"" forState:UIControlStateNormal];
    [btn_LogIn addTarget:self action:@selector(ClickOnLogIn) forControlEvents:UIControlEventTouchUpInside];
    [btn_LogIn retain];

    NSString *deviceVersion=[UIDevice currentDevice].systemVersion;
    NSLog(@"%@",deviceVersion);

    btn_Back=[UIButton buttonWithType:UIButtonTypeCustom];
    btn_Back.frame=CGRectMake(8, 417, 50, 40);
    btn_Back.backgroundColor=[UIColor clearColor];
    [btn_Back setTitle:@"" forState:UIControlStateNormal];
    [btn_Back addTarget:self action:@selector(ClickOnBack) forControlEvents:UIControlEventTouchUpInside];
    [btn_Back retain];

    return self;
}

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView 
{
    [super loadView];
    [self.view addSubview:img_loginBg];
    [self.view addSubview:btn_SignUp];
    [self.view addSubview:btn_LogIn];
    [self.view addSubview:btn_Back];
    [self.view addSubview:UserIDtxt];
    [self.view addSubview:pwdText];
}

-(void)ClickOnSignUp
{
    Connection=[[NetworkConnection alloc]initConnection];
    if (Connection.isReachable)
    {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.foodstoragemanagement.com/signup.php"]];
    }
    else 
    {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Inventory" message:@"Network Connection unavailable.."  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginError show];
        [LoginError release];

    }
}

-(void) startSpinner:(NSString*)type andDisplay:(NSString*)display{

    //remove any existing spinners at this point

    if(self.spinnerView)
    {
        [self.spinnerView.view removeFromSuperview];
        self.spinnerView = nil;
    }
    self.spinnerView =[[[SpinnerModal alloc]initWithType:type andDisplay:display]autorelease];
    //add this to the root view of the app
    //ViewManager *viewMgr = [ViewManager getManager];
    [self.view addSubview:self.spinnerView.view];   
}

-(void) stopSpinner{
    NSLog(@"SPINNER IS REMOVED");
    [self.spinnerView.view removeFromSuperview];
    self.spinnerView = nil;
}

-(void)ClickOnLogIn
{
    Connection=[[NetworkConnection alloc]initConnection];
    if (Connection.isReachable)
    {
        [self startSpinner:@"spinner" andDisplay:@"Loading"];
        timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(ClickOnLog) userInfo:nil repeats:NO];
    }
    else {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Inventory" message:@"Network Connection unavailable.."  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [LoginError show];
                [LoginError release];
        [self stopSpinner];
    }

}

-(void)ClickOnLog
{
    NSDate* now = [NSDate date];
    NSString *dateString=[[NSString alloc]init];
    dateString = [now description];
    dateString=[self dateInFormat:@"%s"];

    NSString *username=[UserIDtxt.text lowercaseString];
    NSString *username_reverse=[username reverseString];

    NSString *password_hash=[self sha256:pwdText.text];

    NSString *str=[NSString stringWithFormat:@"%@%@%@",username,password_hash,dateString];
    str=[self sha256:str];
    app.username=[NSMutableString stringWithString:username];
    app.password=[NSMutableString stringWithString:password_hash];

    //url from plist
    NSString *server=[[NSString alloc]init];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
    NSMutableDictionary *plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    server=[plistDict objectForKey:@"NewUrl"];

    XMLRPCRequest *reqHello = [[XMLRPCRequest alloc] initWithHost:[NSURL URLWithString:server]];
    NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];

    [dict setValue:[UserIDtxt.text lowercaseString] forKey:@"username"];
    [dict setValue:str forKey:@"hash_key"];
    [dict setValue:dateString forKey:@"timestamp"];


    [reqHello setMethod:@"user.get_api" withObjects:[NSArray arrayWithObjects:dict,nil]];

    NSString *result=[self executeXMLRPCRequest:reqHello];
    if ([result length]>0)
    {   
        NSLog(@"OUTPUT %@",result);
        NSData* data=[result dataUsingEncoding:NSUTF8StringEncoding];
        NSXMLParser *parser1=[[NSXMLParser alloc]initWithData:data];
        [parser1 setDelegate:self];
        [parser1 parse];
        [reqHello release];

        defaults = [NSUserDefaults standardUserDefaults];
        app.defaultuser=[NSUserDefaults standardUserDefaults];
        [defaults setObject: app.globalApi_key forKey: @"api_key"];
        [defaults setObject:UserIDtxt.text forKey:@"username"];
        [defaults setObject:pwdText.text forKey:@"password"];
        app.defaultuser=defaults;   

        if (!app.globalApi_key)
        {
            defaults = [NSUserDefaults standardUserDefaults];
        }
        [defaults synchronize];
        if (!val)
        {
            val=[defaults objectForKey:@"api_key"];
        }

    }
    else 
    {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Inventory" message:@"Unable to communicate with the server"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginError show];
        [LoginError release];
    }

    if( ![result isKindOfClass:[NSString class]] )//error occured
    {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Inventory" message:@"unable to communicate with server"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginError show];
        [LoginError release];
    }
    else 
    {
        if ([self.validuser isEqualToString:@"Authenticated Successfully"])
        {
            if (app.Authorisation==TRUE) 
            {
                UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:@"Authentication" message:@"Authenticated successfully!!!"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [LoginOK show];
                [LoginOK release];
            }   
            else 
            {
                MainViewController *main=[[MainViewController alloc]init];
                [self.navigationController pushViewController:main animated:YES];
                [main release];

            }
        }
        else 
        {
            UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Authentication" message:self.validuser  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [LoginError show];
            [LoginError release];
        }
    } 
    [self stopSpinner];
}

- (void)alertView:(UIAlertView *)ConfirmationAlert didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if([ConfirmationAlert.title isEqualToString:@"Authentication"])

    {
        [self dismissModalViewControllerAnimated:YES];
        app.Authorisation=FALSE;
    }
}

# pragma mark Parsing Delegate Methods
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
    if([elementName isEqualToString:@"params"])
    {
        Obj_string = [[NSMutableString alloc]init];
        LoginState =[[NSMutableString alloc]init];
        hashkey=[[NSMutableString alloc]init];
        validuser=[[NSMutableString alloc]init];

    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if([elementName isEqualToString:@"name"])
    {
        self.LoginState=self.Obj_string;
    }
    else if([elementName isEqualToString:@"string"])
    {
        //NSLog(@"%@",Obj_string);
        if([self.LoginState isEqualToString:@"hash_key"])
        {
            self.hashkey=self.Obj_string;
            app.globalhash_key=self.hashkey;
        }
        if([self.LoginState isEqualToString:@"api"])
        {
            self.apikey=self.Obj_string;
            app.globalApi_key=self.apikey;
        }
        if([self.LoginState isEqualToString:@"message"])
        {
            self.validuser=self.Obj_string;
        }
    }

    [Obj_string release];
    Obj_string = nil;
    Obj_string = [[NSMutableString alloc]init];
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    [Obj_string appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
    //[LoginState appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];

}


-(NSString *)dateInFormat:(NSString*)stringFormat {
    char buffer[80];
    const char *format = [stringFormat UTF8String];
    time_t rawtime;
    struct tm * timeinfo;
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    strftime(buffer, 80, format, timeinfo);
    return [NSString  stringWithCString:buffer encoding:NSUTF8StringEncoding];
}

- (NSString *)sha256:(NSString *)str
{   
    const char *inputString = [str UTF8String];
    unsigned char hashedChars[32]; // 32bit encoding
    //unsigned char hashedChars[64]; // 64 bit encoding
    //unsigned char hashedChars[64]; //16 bit encoding
    CC_SHA256(inputString , strlen(inputString), hashedChars);
    NSData *hashedData = [NSData dataWithBytes:hashedChars length:32];//32bit encoding
    //NSData *hashedData = [NSData dataWithBytes:hashedChars length:64]; //64bit encoding
    //NSData *hashedData = [NSData dataWithBytes:hashedChars length:16]; //16bit encoding

    NSLog(@"hashedData = %@", hashedData);
    NSString *someString = [NSString stringWithFormat:@"%@", hashedData];

    someString = [someString stringByReplacingOccurrencesOfString:@" " withString:@""];
    someString = [someString stringByReplacingOccurrencesOfString:@"<" withString:@""];
    someString = [someString stringByReplacingOccurrencesOfString:@">" withString:@""];
    //return hash;
    return someString;
}

- (NSString *)getMD5FromString:(NSString *)source
{
    const char *src = [source UTF8String];
    unsigned char result[16];
    CC_MD5(src, strlen(src), result);
    NSString *ret = [[[NSString alloc] initWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                      result[0], result[1], result[2], result[3],
                      result[4], result[5], result[6], result[7],
                      result[8], result[9], result[10], result[11],
                      result[12], result[13], result[14], result[15]
                      ] autorelease];
    return [ret lowercaseString];
}

- (id)executeXMLRPCRequest:(XMLRPCRequest *)req
{
    XMLRPCResponse *userInfoResponse = [XMLRPCConnection sendSynchronousXMLRPCRequest:req];
    return [userInfoResponse object];
}

-(void)ClickOnBack
{
    [self dismissModalViewControllerAnimated:YES];
    //[self.navigationController popViewControllerAnimated:YES];
    //MainViewController *mainView=[[MainViewController alloc]init];
//  [self.navigationController popToViewController:mainView animated:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
    NSInteger nextTag = textField.tag + 1;
    // Try to find next responder
    UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
    if (nextResponder) {
        // Found next responder, so set it.
        [nextResponder becomeFirstResponder];
    } else {
        // Not found, so remove keyboard.
        [textField resignFirstResponder];
    }
    return NO; // We do not want UITextField to insert line-breaks.
}

-(NSString*) digest:(NSString*)input  
{  

    NSData *data = [input dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
  //  uint8_t digest[CC_SHA1_DIGEST_LENGTH];  
    uint8_t digest[CC_SHA256_DIGEST_LENGTH];  

    CC_SHA1(data.bytes, data.length, digest);  
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];  

   // for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)  

        for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)  

        [output appendFormat:@"%02x", digest[i]];  

    return output;  

}  


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

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

The part in question is this

if ([self.validuser isEqualToString:@"Authenticated Successfully"])
    {
        if (app.Authorisation==TRUE) 
        {
            UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:@"Authentication" message:@"Authenticated successfully!!!"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [LoginOK show];
            [LoginOK release];
        }   
        else 
        {
            MainViewController *main=[[MainViewController alloc]init];
            [self.navigationController pushViewController:main animated:YES];
            [main release];

        }
    }
    else 
    {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Authentication" message:self.validuser  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginError show];
        [LoginError release];
    }
} 

On the surface it seems really simple. The change I want to make is to remove this alert

UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:@"Authentication" message:@"Authenticated successfully!!!"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [LoginOK show];
                [LoginOK release];

However, any change to the alert causes the pushViewController to stop working. I have tried commenting the alert out,

if ([self.validuser isEqualToString:@"Authenticated Successfully"])
    {
    if (app.Authorisation==TRUE) 
    {
       // UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:@"Authentication" message:@"Authenticated successfully!!!"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        //[LoginOK show];
        //[LoginOK release];
    }   
    else 
    {
        MainViewController *main=[[MainViewController alloc]init];
        [self.navigationController pushViewController:main animated:YES];
        [main release];

    }
    }
    else 
    {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Authentication" message:self.validuser  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginError show];
        [LoginError release];
    }
} 

I have tried rewriting the second if

if ([self.validuser isEqualToString:@"Authenticated Successfully"])
    {
    if (app.Authorisation==FALSE) 
    {

        MainViewController *main=[[MainViewController alloc]init];
        [self.navigationController pushViewController:main animated:YES];
        [main release];

    }
    }
    else 
    {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Authentication" message:self.validuser  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginError show];
        [LoginError release];
    }
} 

I have also tried completely removing the second if

if ([self.validuser isEqualToString:@"Authenticated Successfully"])
    {

        MainViewController *main=[[MainViewController alloc]init];
        [self.navigationController pushViewController:main animated:YES];
        [main release];


    }
    else 
    {
        UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Authentication" message:self.validuser  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginError show];
        [LoginError release];
    }
} 

But the pushViewController will not work unless I have the alert in the code. I don't get any error, and the app does not crash, it just stays in the current page, so I am completely at a loss. It makes me think their is some action that is triggered by clicking "OK" in the alert, but I don't see anything in the code.

I have also stepped through the code to see if I can spot the problem but it seems fine.

In case it matters I am using xcode 4.2 and iOS 5 sdk.

Another strange occurance is that if I run the code like this

if ([self.validuser isEqualToString:@"Authenticated Successfully"])
        {

                MainViewController *main=[[MainViewController alloc]init];
                [self.navigationController pushViewController:main animated:YES];
                [main release];

        }
        else 
        {
            UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:@"Authentication" message:self.validuser  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [LoginError show];
            [LoginError release];
        }

and I get a login error (meaning it triggers the alert in the else). Then after clicking ok it moves on to the next page. I really don't understand how this could happen since they are in different part of the if. I must be missing something obvious.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我不吻晚风 2024-12-18 07:58:05

Uialertview 委托方法永远不会被调用,因此永远不会关闭模式视图控制器

- (void)alertView:(UIAlertView *)ConfirmationAlert didDismissWithButtonIndex:(NSInteger)buttonIndex

只需关闭注释代码旁边的视图控制器

[self dismissModalViewControllerAnimated:YES];
app.Authorisation=FALSE;

The Uialertview delegate method never gets called, therefore never dismisses the modal view controller

- (void)alertView:(UIAlertView *)ConfirmationAlert didDismissWithButtonIndex:(NSInteger)buttonIndex

Just dismiss the view controller next to the commented code

[self dismissModalViewControllerAnimated:YES];
app.Authorisation=FALSE;
假扮的天使 2024-12-18 07:58:05

我可能完全没有根据,但是你是否尝试删除整个块?

if (app.Authorisation==TRUE) 
    { ***STARTING HERE
        UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:@"Authentication" message:@"Authenticated successfully!!!"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginOK show];
        [LoginOK release];
    }   
    else 
    {
        MainViewController *main=[[MainViewController alloc]init];
        [self.navigationController pushViewController:main animated:YES];
        [main release];

    } ***ENDING HERE
}

I may be totally off base here, but did you try removing the entire block;

if (app.Authorisation==TRUE) 
    { ***STARTING HERE
        UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:@"Authentication" message:@"Authenticated successfully!!!"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [LoginOK show];
        [LoginOK release];
    }   
    else 
    {
        MainViewController *main=[[MainViewController alloc]init];
        [self.navigationController pushViewController:main animated:YES];
        [main release];

    } ***ENDING HERE
}
-柠檬树下少年和吉他 2024-12-18 07:58:05

如果删除警报,则不会调用委托方法。
这部分在这里:

- (void)alertView:(UIAlertView *)ConfirmationAlert didDismissWithButtonIndex:(NSInteger)buttonIndex {
      if([ConfirmationAlert.title isEqualToString:@"Authentication"]) {
          [self dismissModalViewControllerAnimated:YES];
          app.Authorisation=FALSE;
      }
}

只需将上面 if 块内的代码放入您删除警报的块中即可。

If you remove the alert then the delegate methods won't be called.
This part here:

- (void)alertView:(UIAlertView *)ConfirmationAlert didDismissWithButtonIndex:(NSInteger)buttonIndex {
      if([ConfirmationAlert.title isEqualToString:@"Authentication"]) {
          [self dismissModalViewControllerAnimated:YES];
          app.Authorisation=FALSE;
      }
}

Just put the code inside the if-block above into the block where you removed the alert.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文