Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/114.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在iOS中获得JSON响应?得到零值?_Php_Ios_Objective C_Json_Web Services - Fatal编程技术网

Php 如何在iOS中获得JSON响应?得到零值?

Php 如何在iOS中获得JSON响应?得到零值?,php,ios,objective-c,json,web-services,Php,Ios,Objective C,Json,Web Services,我正在将数据从phpapi发送到我的ios应用程序 获取JSON响应时出现问题 @interface CPDScatterPlotViewController () { NSURLConnection *conGet; } @end @implementation CPDScatterPlotViewController @synthesize responseData; - (void)viewDidLoad { [super viewDidLoad]; NSL

我正在将数据从php
api
发送到我的ios应用程序

获取
JSON
响应时出现问题

@interface CPDScatterPlotViewController ()
{
    NSURLConnection *conGet;
}
@end

@implementation CPDScatterPlotViewController
@synthesize responseData;


- (void)viewDidLoad
{
    [super viewDidLoad];

    NSLog(@"viewdidload");
     self.responseData = [NSMutableData data];
    NSURLRequest *request = [NSURLRequest requestWithURL:
                             [NSURL URLWithString:@"http://localhost/testApi/test_api.php?method=hello"]];

 conGet =[[NSURLConnection alloc] initWithRequest:request delegate:self];

    NSLog(@"Request sent");

    NSString* responseString = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding] ;

    NSLog(@"Response String: %@", responseString);
    NSLog(@"val : %@ ", responseData);


}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"didReceiveResponse");
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"didFailWithError");
    NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"connectionDidFinishLoading");
    NSLog(@"Succeeded! Received %d bytes of data",[self.responseData length]);

    // convert to JSON
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];

    // show all values
    for(id key in res) {

        id value = [res objectForKey:key];

        NSString *keyAsString = (NSString *)key;
        NSString *valueAsString = (NSString *)value;

        NSLog(@"key: %@", keyAsString);
        NSLog(@"value: %@", valueAsString);
    }

    // extract specific value...
    NSArray *results = [res objectForKey:@"results"];

    for (NSDictionary *result in results) {
        NSString *icon = [result objectForKey:@"icon"];
        NSLog(@"icon: %@", icon);
    }

}
这是我试图得到响应的代码

@interface CPDScatterPlotViewController ()
{
    NSURLConnection *conGet;
}
@end

@implementation CPDScatterPlotViewController
@synthesize responseData;


- (void)viewDidLoad
{
    [super viewDidLoad];

    NSLog(@"viewdidload");
     self.responseData = [NSMutableData data];
    NSURLRequest *request = [NSURLRequest requestWithURL:
                             [NSURL URLWithString:@"http://localhost/testApi/test_api.php?method=hello"]];

 conGet =[[NSURLConnection alloc] initWithRequest:request delegate:self];

    NSLog(@"Request sent");

    NSString* responseString = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding] ;

    NSLog(@"Response String: %@", responseString);
    NSLog(@"val : %@ ", responseData);


}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"didReceiveResponse");
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"didFailWithError");
    NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"connectionDidFinishLoading");
    NSLog(@"Succeeded! Received %d bytes of data",[self.responseData length]);

    // convert to JSON
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];

    // show all values
    for(id key in res) {

        id value = [res objectForKey:key];

        NSString *keyAsString = (NSString *)key;
        NSString *valueAsString = (NSString *)value;

        NSLog(@"key: %@", keyAsString);
        NSLog(@"value: %@", valueAsString);
    }

    // extract specific value...
    NSArray *results = [res objectForKey:@"results"];

    for (NSDictionary *result in results) {
        NSString *icon = [result objectForKey:@"icon"];
        NSLog(@"icon: %@", icon);
    }

}
但是当我运行这段代码时,我得到了一个异常

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因是:“数据参数为零”

这是我的API文件

<?php>
function deliver_response($format, $api_response)
{
// Define HTTP responses
    $http_response_code = array(
        200 => 'OK',
        400 => 'Bad Request',
        401 => 'Unauthorized',
        403 => 'Forbidden',
        404 => 'Not Found'
    );
// Set HTTP Response
    header('HTTP/1.1 ' . $api_response['status'] . ' ' . $http_response_code[$api_response['status']]);
// Process different content types
    if (strcasecmp($format, 'json') == 0)
    {
// Set HTTP Response Content Type
        header('Content-Type: application/json; charset=utf-8');
// Format data into a JSON response
        $json_response = json_encode($api_response);
// Deliver formatted data
        echo $json_response;
    }
    elseif (strcasecmp($format, 'xml') == 0)
    {
// Set HTTP Response Content Type
        header('Content-Type: application/xml; charset=utf-8');
// Format data into an XML response (This is only good at handling string data, not arrays)
        $xml_response = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" .
                '<response>' . "\n" .
                "\t" . '<code>' . $api_response['code'] . '</code>' . "\n" .
                "\t" . '<data>' . $api_response['data'] . '</data>' . "\n" .
                '</response>';
// Deliver formatted data
        echo $xml_response;
    }
    else
    {
// Set HTTP Response Content Type (This is only good at handling string data, not arrays)
        header('Content-Type: text/html; charset=utf-8');
// Deliver formatted data
        echo $api_response['data'];
    }
// End script process
    exit;
}

//////////My SQL Connection
// Create connection
$con = mysqli_connect("", "root", "", "test_db");

// Check connection
if (mysqli_connect_errno($con))
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con, "SELECT count(*) FROM test_table");

//$count = $result->num_rows;

// Define whether an HTTPS connection is required
$HTTPS_required = FALSE;
// Define whether user authentication is required
$authentication_required = FALSE;
// Define API response codes and their related HTTP response
$api_response_code = array(
    0 => array('HTTP Response' => 400, 'Message' => 'Unknown Error'),
    1 => array('HTTP Response' => 200, 'Message' => 'Success'),
    2 => array('HTTP Response' => 403, 'Message' => 'HTTPS Required'),
    3 => array('HTTP Response' => 401, 'Message' => 'Authentication Required'),
    4 => array('HTTP Response' => 401, 'Message' => 'Authentication Failed'),
    5 => array('HTTP Response' => 404, 'Message' => 'Invalid Request'),
    6 => array('HTTP Response' => 400, 'Message' => 'Invalid Response Format')
);
// Set default HTTP response of 'ok'
$response['code'] = 0;
$response['status'] = 404;
$response['data'] = NULL;
// --- Step 2: Authorization
// Optionally require connections to be made via HTTPS
if ($HTTPS_required && $_SERVER['HTTPS'] != 'on')
{
    $response['code'] = 2;
    $response['status'] = $api_response_code[$response['code']]['HTTP Response'];
    $response['data'] = $api_response_code[$response['code']]['Message'];


// Return Response to browser. This will exit the script.
    deliver_response($_GET['format'], $response);
}
// Optionally require user authentication
if ($authentication_required)
{

    if (empty($_POST['username']) || empty($_POST['password']))
    {
        $response['code'] = 3;
        $response['status'] = $api_response_code[$response['code']]['HTTP Response'];
        $response['data'] = $api_response_code[$response['code']]['Message'];
    }
// Return an error response if user fails authentication. This is a very simplistic example
// that should be modified for security in a production environment
    elseif ($_POST['username'] != 'foo' && $_POST['password'] != 'bar')
    {
        $response['code'] = 4;
        $response['status'] = $api_response_code[$response['code']]['HTTP Response'];
        $response['data'] = $api_response_code[$response['code']]['Message'];
    }
}
// --- Step 3: Process Request
// Method A: Say Hello to the API
//$_GET['method'] = 'hello';
if (strcasecmp($_GET['method'], 'hello') == 0)
{
    $response['code'] = 1;
    $response['status'] = $api_response_code[$response['code']]['HTTP Response'];

    $row = $result->fetch_row();
   // echo $row[0];
    $response['data'] = $row[0];   
}
// --- Step 4: Deliver Response
// Return Response to browser
deliver_response("json", $response);
?>

如果我运行这个Api,它将在网页上显示记录8346。

对代码进行这些更改

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        NSLog(@"connectionDidFinishLoading");
        NSLog(@"Succeeded! Received %d bytes of data",[self.responseData length]);
        NSString *strr = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
        NSLog(@"data is: %@",self.responseData);

    //NSDictionary *dict = [[NSDictionary alloc] initwithd]


    // convert to JSON

    NSError *e = nil;
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: _responseData options:NSJSONReadingMutableContainers error:&e];

    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:nil];
    NSLog(@"data -- %@",[dict objectForKey:@"data"]);
    if (!jsonArray) {
        NSLog(@"Error parsing JSON: %@", e);
    } 

在我的情况下,我使用了这个

 NSString* urlString=[NSString stringWithFormat:@“%@“,myURLwithKeyAndValue];
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];


    NSData * results = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];

    NSLog(@"Result  = %@",results);

    if (results)
    {

        messageDataDict = [NSJSONSerialization JSONObjectWithData: results options: NSJSONReadingMutableContainers error: nil];

    }