NSURLRequest 身份验证不起作用

发布于 2024-10-20 11:07:01 字数 7005 浏览 2 评论 0原文

好吧,我创建了一个 NSLURLRequest ,它应该从服务器获取字符串并将其带回到程序中。根据返回的字符串,程序应该转换到不同的视图。由于某种原因,即使控制台返回正确的字符串,条件语句中的方法也不会被执行。这是我的代码:

#import "login.h"


@implementation login

@synthesize viewController;
@synthesize viewControllerTwo;
@synthesize userName;
@synthesize passWord;
@synthesize verified;
@synthesize receivedData;
@synthesize requestType;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
    // Custom initialization
}
return self;
}
*/

-(IBAction)login{
 [self performSelector:@selector(getAuthentication) withObject:nil afterDelay:0.5];
 //[self performSelector:@selector(authenticate) withObject:nil afterDelay:5.0];
}

-(void)authenticate{
NSString *good = @"Done";
NSLog(@"%@", good);
  if(verified == good){
            [self performSelector:@selector(changeViewAdmin) withObject:nil afterDelay:1.0];
        }
        if(verified == @"user"){
            [self performSelector:@selector(changeView) withObject:nil afterDelay:1.0];
        }
        if(verified == @"No"){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
    message:@"Invalid UserName/Password combination!"
    delegate:self
    cancelButtonTitle:@"Okay"
    otherButtonTitles:nil];
    [alert show];
    [alert release];
        }
    }

-(void)getAuthentication{
requestType = 1;
NSMutableString *urlWithParameters = [NSMutableString stringWithString:kLoginURL];

[urlWithParameters appendFormat:@"?userName=%@&passWord=%@", userName.text, passWord.text];

NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlWithParameters]];

//NSLog(@"%@", req);

 NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
   if(theConnection){
    NSMutableData *data = [[NSMutableData alloc] init];
    self.receivedData = data;
    [data release];
  }
[userName resignFirstResponder];
[passWord resignFirstResponder];
[req release];
}

-(void)changeView{
    CATransition *transition = [CATransition animation];
    transition.duration = 0.5;
    transition.timingFunction = [CAMediaTimingFunction 
                                 functionWithName:kCAMediaTimingFunctionEaseOut];
    transition.delegate = self;

    transition.type = kCATransitionMoveIn;
    transition.subtype = kCATransitionFromRight;

    [self.view.layer addAnimation:transition forKey:@"transition3"];
    viewController = [[MapMeViewController alloc] initWithNibName:@"MapMeViewController" bundle:[NSBundle mainBundle]];
    [self.view addSubview:viewController.view];
}

-(void)changeViewAdmin{
    CATransition *transition = [CATransition animation];
    transition.duration = 0.5;
    transition.timingFunction = [CAMediaTimingFunction 
                                 functionWithName:kCAMediaTimingFunctionEaseOut];
    transition.delegate = self;

    transition.type = kCATransitionMoveIn;
    transition.subtype = kCATransitionFromRight;

    [self.view.layer addAnimation:transition forKey:@"transition3"];
    viewControllerTwo = [[AdminPanel alloc] initWithNibName:@"AdminPanel" bundle:[NSBundle mainBundle]];
    [self.view addSubview:viewControllerTwo.view];
}


// 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 {
    [viewController release];
    [viewControllerTwo release];
    [userName release];
    [passWord release];
    [verified release];
    [receivedData release];
    [super dealloc];
}

#pragma mark -
#pragma mark NSURLConnection Callbacks
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection 
  didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
  /*// Access has failed two times...
  if ([challenge previousFailureCount] > 1)
  {
    [kFormURL release];


UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Authentication Error"
                                 message:@"Too many unsuccessul login attempts." 
                                 delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

[alert show];
[alert release];
  }
  else 
  {*/
    // Answer the challenge
    NSURLCredential *cred = [[[NSURLCredential alloc] initWithUser:@"//rightusername" password:@"//rightpassword"
       persistence:NSURLCredentialPersistenceForSession] autorelease];
    [[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
  //}
    }

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[connection release];
self.receivedData = nil;

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:[NSString stringWithFormat:@"Connection failed! Error - %@ (URL: %@)",[error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]]
delegate:self
cancelButtonTitle:@"Bummer"
otherButtonTitles:nil];
[alert show];
[alert release];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *payloadAsString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
verified = payloadAsString;
[payloadAsString release];
 NSLog(@"%@", verified);
  if(verified == @"Done"){
        [self performSelector:@selector(changeViewAdmin) withObject:nil afterDelay:1.0];
    }
//[payloadAsString release];
//NSLog(@"%@", verified);
//  INSERT GOOGLE MAPS URL REQUEST HERE
/*if(requestType == 1){
NSString* addressText = payloadAsString;
// URL encode the spaces
addressText =  [addressText stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding];  
NSString* urlText = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@", addressText];
// lets throw this text on the log so we can view the url in the event we have an issue
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlText]];
// */
//
//}
[connection release];
self.receivedData = nil;
}


@end

Alrighty, so I've created a NSLURLRequest that's supposed to fetch a string from the server and bring it back into the program. Depending on the string returned, the program is supposed to transition into a different view. For some reason, even though the console returns the correct string, the method inside the conditional statement is not being performed. Here's my code:

#import "login.h"


@implementation login

@synthesize viewController;
@synthesize viewControllerTwo;
@synthesize userName;
@synthesize passWord;
@synthesize verified;
@synthesize receivedData;
@synthesize requestType;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
    // Custom initialization
}
return self;
}
*/

-(IBAction)login{
 [self performSelector:@selector(getAuthentication) withObject:nil afterDelay:0.5];
 //[self performSelector:@selector(authenticate) withObject:nil afterDelay:5.0];
}

-(void)authenticate{
NSString *good = @"Done";
NSLog(@"%@", good);
  if(verified == good){
            [self performSelector:@selector(changeViewAdmin) withObject:nil afterDelay:1.0];
        }
        if(verified == @"user"){
            [self performSelector:@selector(changeView) withObject:nil afterDelay:1.0];
        }
        if(verified == @"No"){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
    message:@"Invalid UserName/Password combination!"
    delegate:self
    cancelButtonTitle:@"Okay"
    otherButtonTitles:nil];
    [alert show];
    [alert release];
        }
    }

-(void)getAuthentication{
requestType = 1;
NSMutableString *urlWithParameters = [NSMutableString stringWithString:kLoginURL];

[urlWithParameters appendFormat:@"?userName=%@&passWord=%@", userName.text, passWord.text];

NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlWithParameters]];

//NSLog(@"%@", req);

 NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
   if(theConnection){
    NSMutableData *data = [[NSMutableData alloc] init];
    self.receivedData = data;
    [data release];
  }
[userName resignFirstResponder];
[passWord resignFirstResponder];
[req release];
}

-(void)changeView{
    CATransition *transition = [CATransition animation];
    transition.duration = 0.5;
    transition.timingFunction = [CAMediaTimingFunction 
                                 functionWithName:kCAMediaTimingFunctionEaseOut];
    transition.delegate = self;

    transition.type = kCATransitionMoveIn;
    transition.subtype = kCATransitionFromRight;

    [self.view.layer addAnimation:transition forKey:@"transition3"];
    viewController = [[MapMeViewController alloc] initWithNibName:@"MapMeViewController" bundle:[NSBundle mainBundle]];
    [self.view addSubview:viewController.view];
}

-(void)changeViewAdmin{
    CATransition *transition = [CATransition animation];
    transition.duration = 0.5;
    transition.timingFunction = [CAMediaTimingFunction 
                                 functionWithName:kCAMediaTimingFunctionEaseOut];
    transition.delegate = self;

    transition.type = kCATransitionMoveIn;
    transition.subtype = kCATransitionFromRight;

    [self.view.layer addAnimation:transition forKey:@"transition3"];
    viewControllerTwo = [[AdminPanel alloc] initWithNibName:@"AdminPanel" bundle:[NSBundle mainBundle]];
    [self.view addSubview:viewControllerTwo.view];
}


// 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 {
    [viewController release];
    [viewControllerTwo release];
    [userName release];
    [passWord release];
    [verified release];
    [receivedData release];
    [super dealloc];
}

#pragma mark -
#pragma mark NSURLConnection Callbacks
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection 
  didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
  /*// Access has failed two times...
  if ([challenge previousFailureCount] > 1)
  {
    [kFormURL release];


UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Authentication Error"
                                 message:@"Too many unsuccessul login attempts." 
                                 delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

[alert show];
[alert release];
  }
  else 
  {*/
    // Answer the challenge
    NSURLCredential *cred = [[[NSURLCredential alloc] initWithUser:@"//rightusername" password:@"//rightpassword"
       persistence:NSURLCredentialPersistenceForSession] autorelease];
    [[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
  //}
    }

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[connection release];
self.receivedData = nil;

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:[NSString stringWithFormat:@"Connection failed! Error - %@ (URL: %@)",[error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]]
delegate:self
cancelButtonTitle:@"Bummer"
otherButtonTitles:nil];
[alert show];
[alert release];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *payloadAsString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
verified = payloadAsString;
[payloadAsString release];
 NSLog(@"%@", verified);
  if(verified == @"Done"){
        [self performSelector:@selector(changeViewAdmin) withObject:nil afterDelay:1.0];
    }
//[payloadAsString release];
//NSLog(@"%@", verified);
//  INSERT GOOGLE MAPS URL REQUEST HERE
/*if(requestType == 1){
NSString* addressText = payloadAsString;
// URL encode the spaces
addressText =  [addressText stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding];  
NSString* urlText = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@", addressText];
// lets throw this text on the log so we can view the url in the event we have an issue
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlText]];
// */
//
//}
[connection release];
self.receivedData = nil;
}


@end

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

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

发布评论

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

评论(1

老娘不死你永远是小三 2024-10-27 11:07:01

哎呀,不,不,不,……

if ( verified == @"Done" )

你在这里比较指针而不是已验证变量内容。您应该使用:

if ( [verified isEqualToString:@"Done"] )

阅读此https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html%23//apple_ref /doc/uid/20000154-SW29

PS格式化你的帖子,它不可读......我不得不编辑它......

Ouch, no, no, no, ...

if ( verified == @"Done" )

... you're comparing pointers here and not verified variable content. You should use:

if ( [verified isEqualToString:@"Done"] )

Read this https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html%23//apple_ref/doc/uid/20000154-SW29

P.S. Format your post, it's unreadable ... I had to edit it ...

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