doushan7997 2013-03-30 01:03
浏览 60
已采纳

如何在JSON中编码MYSQL响应并在iOS应用程序中解析

my php has a method called load. I am able to insert on a different method, but when I change the parameters to speak to this method, I think it sends the data correctly but it's not showing up on my app.

index.php

function load(){
          //Establish connection
   $con=mysqli_connect("localhost","root","","Mealidea");

    // Check connection
    if (mysqli_connect_errno()){
        $errorR['name']="Failed to connect to mysql".mysqli_connect_error();
        echo json_encode(errorR);
    }

    //Perform query
    $result = mysqli_query($con,"SELECT * FROM User");
    $myjsons = array();

    while($row = mysql_fetch_assoc($result)){ 
        $myjsons[] = $row;
    }

    //Close connection
    mysqli_close($con);    

    echo json_encode($myjsons);
}

Set request:

//Get from DB
    NSURL*url=[NSURL URLWithString:@"http://localhost/Tutorials/index.php?f=load&key=6dM7V0n5GqYJLTMibQDf2gA2a94h8hbF"];

    //URL request
    NSURLRequest*request=[NSURLRequest requestWithURL:url];


    //Set the connection
    connection = [NSURLConnection connectionWithRequest:request delegate:self];

    if (connection) {
        webData=[[NSMutableData alloc]init];
    }

Get answer:

NSDictionary*data=[NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];

    //If data is nil, then print error
    if (data==nil) {
        //NSLog(@"%@",error);
    }

    //Print the data
    NSLog(@"%@",data);

    //???? how to parse data?
    NSDictionary*num=[data valueForKey:@"User"];
  • 写回答

1条回答 默认 最新

  • douzhong1730 2013-03-30 01:18
    关注

    Your PHP script appears to be sending an array (encoded in JSON), but your Objective-C code appears to expect an NSDictionary, according to this line:

    NSDictionary*data=[NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
    

    That should probably be

    NSArray *users = [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
    

    And then you should be able to iterate over the NSArray of users, and present them in a UITableView or something similar.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染