dongna2498 2014-09-13 06:57
浏览 34
已采纳

将JSON与xcode一起使用(从数据库返回用户信息)

I'm trying to create the login process (which is working at the moment) and at the same time, I would like to "load" user stats (those stats are in my database). I'm trying to use JSON, but I'm not an expert in this language and I need some help.

First, I would like to know if I'm doing this right, because it's not returning any value (NULL). You can see my PHP file, where is set the JSON code.

Is everything right? How can I pass the values using JSON to the xcode? Like I said, I need some help because I never used JSON and I'm not sure that I'm doing this right.

That's my login PHP file: (it launches when the user clics on the "LOGIN" button).

    <?php
header('Content-type: application/json');
if($_POST) {

    $DB_HostName = "localhost";
    $DB_Name = "db";
    $DB_User = "user";
    $DB_Pass = "pass";

    $userName = $_POST["username"];
    $password = $_POST["password"];

    $sql = "select * from user where userName = '$userName' and password = '$password';";
    $con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());

    mysql_select_db($DB_Name,$con) or die(mysql_error());

    $res = mysql_query($sql,$con) or die(mysql_error());
    $res1 = mysql_num_rows($res);

    if ($res1>0)
    {
        //
        $query = mysql_query("select * from user where userName = '$userName' and password = '$password';");
        while ($row = mysql_fetch_array($query))
        {
            $id=$row['userID'];
        }
        $query2 = mysql_query("select * from user_stats where userID = '$id';");
        while ($row2 = mysql_fetch_array($query2))
        {
            $followers=$row2['followers'];
            $stars=$row2['stars'];
            $photos=$row2['photos'];
            $data=$followers.'-'.$stars.'-'.$photos;
        }
        //die(json_encode(array("message" => "Getting user information succeeded.", "status" => '"success":1', "data" => $data), JSON_PRETTY_PRINT));
        //
        echo '{"success":1,"data":'.$data.'}';
    }
    else
    {
        echo '{"success":0,"error_message":"Username and/or password is invalid.1"}';
    }
}
else
{
    echo '{"success":0,"error_message":"Username and/or password is invalid.2"}';
}

ViewController.m

- (IBAction)loginClicked:(id)sender {
@try {

    if([[_txtUsername text] isEqualToString:@""] || [[_txtPassword text] isEqualToString:@""] ) {
        [self alertStatus:@"Porfavor, introduce el usuario y contraseña" :@"Error"];
    } else {
        NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[_txtUsername text],[_txtPassword text]];
        NSLog(@"PostData: %@",post);

        NSURL *url=[NSURL URLWithString:@"http://autograpp.com/login.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);

            SBJsonParser *jsonParser = [SBJsonParser new];
            NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
            NSLog(@"%@",jsonData);
            NSInteger success = [(NSNumber *) [jsonData objectForKey:@"success"] integerValue];
            NSLog(@"%ld",(long)success);

            NSString *data = [(NSNumber *) [jsonData objectForKey:@"data"] stringValue];
            NSLog(@"%@",data);

            if(success == 1)
            {
                NSLog(@"Login SUCCESS");
                //[self alertStatus:@"Bienvenido a Autograpp." :@"Datos correctos"];
                [self performSegueWithIdentifier:@"Main" sender:self];

            } else {

                NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message"];
                [self alertStatus:error_msg :@"Datos incorrectos"];
            }
            /*
            NSString *jsonString = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
            NSData *JSONdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
            NSError *jsonError = nil;
            if (JSONdata != nil) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
                if (jsonError == nil) {
                    // Set your text fields here.
                    NSLog(@"%@",dic);
                }
            }
            */

        } else {
            if (error) NSLog(@"Error: %@", error);
            [self alertStatus:@"Ha ocurrido un problema inesperado" :@"Error"];
        }
    }
}
@catch (NSException * e) {
    NSLog(@"Exception: %@", e);
    [self alertStatus:@"Error." :@"Error"];
}

The problem is: When I try to read the values from the JSON they are NULL. I think it's because I'm not an expert using the JSON code and there is something wrong.

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongrou5254 2014-09-13 07:28
    关注

    Do something like this

    NSString *link = [NSString stringWithFormat:@"http://autograpp.com/login.php"];
    
    
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:link]];
        [request setRequestMethod:@"POST"];
        [request addRequestHeader:@"Content-Type" value:@"application/json"];
        [request addRequestHeader:@"Accept" value:@"application/json"];
    
        [request setPostValue:[NSString stringWithFormat:@"%@",  _txtUsername.text] forKey:@"username"];
        [request setPostValue:[NSString stringWithFormat:@"%@",  _txtPassword.text] forKey:@"password"];
    
    
        [request startSynchronous];
    
        NSError *error = [request error];
        if (!error) {
            NSString *jsonString = [request responseString];
            if(kShowLog)
                NSLog(@"response: %@", jsonString);
            NSDictionary * returnDict = (NSDictionary *) [jsonString JSONValue];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog