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 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图