1

我在 PHP 中创建了 Web 服务,它有 1 个函数和 1 个参数。我使用 phpMyadmin 作为后端。它使用 json 格式来获取数据。Web 服务运行良好。我想在我的 iPhone 应用程序中使用这个网络服务。我想传递 1 个参数。我也将 rayWenderlich 教程作为参考。但找不到解决办法。请帮帮我。

这是我的网络服务代码:

<?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 端,我尝试过以下代码:

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

}
}
4

1 回答 1

0

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

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

}];  

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

于 2012-10-03T05:25:52.660 回答