json解析在ios + php中 [英] json parsing in ios+php

查看:135
本文介绍了json解析在ios + php中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHP中创建了具有1个参数的1个函数的web服务。
我使用phpMyadmin作为后端。
它使用json格式获取数据。
Web服务工作正常。
我想在我的iPhone应用程序中使用此Web服务。
我想传递1个参数。
我也提到了rayWenderlich教程。
但找不到解决方案。
请帮助我。



这是我的网络服务代码:

 <?php 

echo getdata($ _ REQUEST ['lastupdate']);

函数getdata($ lastupdatedate){

$ json ='{foo-bar:12345}';
$ obj = json_decode($ json);
// print $ obj-> {'foo-bar'}; // 12345

$ con = mysql_connect(localhost,un,Password);

if(!$ con){
die('Could not connect:'。mysql_error());
}

// print_r($ con);
mysql_select_db(roster,$ con);

$ query =select * from rates where LastUpdated ='。$ lastupdatedate。'by LastUpdated limit 1;
$ rs = mysql_query($ query)或die($ query);

// print_r($ rs);

while($ row = mysql_fetch_assoc($ rs)){
$ record [] = $ row;
}
$ data = json_encode($ record);

header('Cache-Control:no-cache,must-revalidate');
header('Expires:Mon,1997年7月26日05:00:00 GMT');
header('Content-type:application / json');

返回$ data;
}

Iphone App端,我已经在下面的代码尝试过了:

   - (void)GETJSONDATA 
{
SBJSON * json = [SBJSON new];
json.humanReadable = YES;
responseData = [NSMutableData data];

NSString * service = @;
NSString * str;
str = @LastUpdated;


NSString * requestString = [NSString stringWithFormat:@{\LastUpdated \:\%@ \},str];

// [[NSUserDefaults standardUserDefaults] setValue:nil forKey:@WRONGANSWER];

NSLog(@request string:%@,requestString);
NSData * requestData = [NSData dataWithBytes:[requestString UTF8String] length:[requestString length]];


NSString * fileLoc = [[NSBundle mainBundle] pathForResource:@URLNameofType:@plist];
NSDictionary * fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString * urlLoc = [fileContents objectForKey:@URL];
urlLoc = [urlLoc stringByAppendingString:@?lastupdate = 2012-09-01 01:00:00];
NSLog(@URL:%@,urlLoc);

NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:urlLoc]];
NSString * postLength = [NSString stringWithFormat:@%d,[requestData length]];
[request setHTTPMethod:@POST];
[request setValue:postLength forHTTPHeaderField:@Content-Length];
[request setValue:@application / jsonforHTTPHeaderField:@Content-Type];
[request setHTTPBody:requestData];

NSError * respError = nil;
NSData * returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:& respError];

$ b $ if(respError)
{
// NSString * msg = [NSString stringWithFormat:@Connection failed!Error - %@%@,
// [respError localizedDescription],
// [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@ACTEC
message:@检查您的网络连接委托:self cancelButtonTitle:@OK
otherButtonTitles:nil];
[alertView show];


}
else
{
NSUserDefaults * dd = [NSUserDefaults standardUserDefaults];
NSString * responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@Resp:%@,responseString);

NSDictionary * results = [responseString JSONValue];
NSLog(@results =%@,results);


$ b


解决方案

您可能想使用库来查看。 AFNetworking 提供了一个名为AFHTTPClient的类,允许您连接到一个安静的Web服务并对其进行简单调用。假设有一个终点,你可以这样做:

pre $ NS $ Dictionary $ { @最近更新时间];

NSString * fileLoc = [[NSBundle mainBundle] pathForResource:@URLNameofType:@plist];
NSDictionary * fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString * urlLoc = [fileContents objectForKey:@URL];
urlLoc = [urlLoc stringByAppendingString:@?lastupdate = 2012-09-01 01:00:00];

AFHTTPClient * client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:urlLoc]];

[client postPath:@endpointparameters:body success:^(AFHTTPRequestOperation * operation,id responseObject){
//对responseObject做某事

}失败:^(AFHTTPRequestOperation *操作,NSError *错误){
//记录错误并继续

}];

您可以在这里找到文档: http://engineering.gowalla.com/AFNetworking/Classes/AFHTTPClient.html


I have created web service in PHP which is having 1 function with 1 parameter. I am using phpMyadmin as back end. It is using json format for fetching data. Web service is working perfectly. I want to use this web service in my iPhone app. I want to pass 1 parameter. I have referred rayWenderlich tutorial also as reference. But can not find the solution. Please help me out.

This is my web service code:

<?php

echo getdata($_REQUEST['lastupdate']);

function getdata($lastupdatedate){

    $json = '{"foo-bar": 12345}';       
    $obj = json_decode($json);
    //print $obj->{'foo-bar'}; // 12345    

    $con = mysql_connect("localhost","un","Password");          

    if (!$con){
       die('Could not connect: ' . mysql_error());
    }

    //print_r($con);            
    mysql_select_db("roster", $con);

    $query = "select * from rates where LastUpdated = '".$lastupdatedate."' order by LastUpdated limit 1";    
    $rs = mysql_query($query) or die($query);

    //print_r($rs);

    while($row=mysql_fetch_assoc($rs)){    
        $record[] = $row;    
    }
    $data = json_encode($record);

    header('Cache-Control: no-cache, must-revalidate');    
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');    
    header('Content-type: application/json');

    return $data;    
}

Iphone App side , I have tried below code:

-(void)GETJSONDATA
{
    SBJSON *json = [SBJSON new];
    json.humanReadable = YES;
    responseData = [NSMutableData data];

    NSString *service = @"";
    NSString *str;
    str = @"LastUpdated";


    NSString *requestString = [NSString stringWithFormat:@"{\"LastUpdated\":\"%@\"}",str];

    // [[NSUserDefaults standardUserDefaults] setValue:nil forKey:@"WRONGANSWER"];

    NSLog(@"request string:%@",requestString);
    NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];


    NSString *fileLoc = [[NSBundle mainBundle] pathForResource:@"URLName" ofType:@"plist"];
    NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
    NSString *urlLoc = [fileContents objectForKey:@"URL"];
    urlLoc = [urlLoc stringByAppendingString:@"?lastupdate=2012-09-01 01:00:00"];
    NSLog(@"URL : %@",urlLoc);

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: 
                                    [NSURL URLWithString: urlLoc]];  
    NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]];
    [request setHTTPMethod: @"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody: requestData];

    NSError *respError = nil;
    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];


    if (respError) 
    {
        //        NSString *msg = [NSString stringWithFormat:@"Connection failed! Error - %@ %@",
        //                         [respError localizedDescription],
        //                         [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]]; 
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"ACTEC" 
                                                            message:@"check your network connection" delegate:self cancelButtonTitle:@"OK" 
                                                  otherButtonTitles:nil];
        [alertView show];


    } 
    else
    {
        NSUserDefaults *dd = [NSUserDefaults standardUserDefaults];
        NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
        NSLog(@"Resp : %@",responseString);

        NSDictionary *results = [responseString JSONValue];
        NSLog(@"results=%@",results);

}
}

解决方案

You might want to look into using a library. AFNetworking provides a class called AFHTTPClient that allows you to connect to a restful web service and make simple calls to it. Assuming an end point, you can do something like this:

NSDictionary *body = [NSDictionary dictionaryWitObject:@"LastUpdated" forKey:@"LastUpdated"];

NSString *fileLoc = [[NSBundle mainBundle] pathForResource:@"URLName" ofType:@"plist"];
NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString *urlLoc = [fileContents objectForKey:@"URL"];
urlLoc = [urlLoc stringByAppendingString:@"?lastupdate=2012-09-01 01:00:00"];    

AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:urlLoc]];

[client postPath:@"endpoint" parameters:body success:^(AFHTTPRequestOperation *operation, id responseObject) {
    // Do something with the responseObject

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // Log the error and proceed

}];  

You can find the docs here: http://engineering.gowalla.com/AFNetworking/Classes/AFHTTPClient.html

这篇关于json解析在ios + php中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆