2014-10-09 124 views
0

我一直在这个问题上停留了一段时间,所以我非常感谢一些帮助。我对iOS应用程序编程非常新颖。我已经开始使用登录应用程序,但我在从php文件获取响应时遇到了一些“登录成功状态”的问题。我刚刚变得“登录失败”。我会给你我的代码。请纠正我的错误。 (ViewController.m)文件的代码//如何从php web文件获取数据到目标C

#import "ViewController.h" 
    #import "SBJson.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)signinclicked:(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://shiv.9gem.net/alka/index1.php"]; 

      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) 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 

          ***(php file code)*** 


    <?php 
    header('content-type:application/json'); 
    $dbhost = 'localhost'; 

    $dbuser = 'shiv9gem_alka'; 

    $dbpass = 'alankritasharma'; 

    $conn = mysql_connect($dbhost, $dbuser, $dbpass); 

    if(!$conn) 

    { 

    die('Could not connect: ' . mysql_error()); 

    } 

    $sql = 'SELECT username,password FROM student'; 



    mysql_select_db('shiv9gem_project'); 

    $retval = mysql_query($sql, $conn); 

    if(! $retval) 

    { 

    die('Could not get data: ' . mysql_error()); 

    } 

    while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) 

    { 


    echo json_encode($row); 
    } 

    echo "Fetched data successfully\n"; 



    if($_POST) 
    { 
    if($_POST['username']=='alankrita' && $_POST['password']=='isha123') 
    { 
    echo '{"success":1}'; 
    } 
    else 
    { 
    echo '{"success":0,"error_message":"username and/or password is invalid."}'; 
    } 
    } else 
    { 
    echo '{"success":0,"error_message":"username and/or password is invalid."}'; } 
    mysql_close($conn);?>  

回答

0

我可以看到在你的代码不一样异步做一些不好的做法,要求或不控制层分离服务器请求层。这背后

离开的时候,我建议你阅读模型 - 视图 - 控制器模式(了解这种模式:http://blog.codinghorror.com/understanding-model-view-controller/

一些,可以帮助你实现请求层RestKit(http://restkit.org/)至极是为iOS,旨在框架与RESTful Web服务进行交互。你可以从RyanWenderlich网站查看这个有用的教程http://www.raywenderlich.com/58682/introduction-restkit-tutorial

希望它有帮助!

+0

非常感谢你的帮助。我会尝试你的建议。 – 2014-10-09 12:53:07