Casper522
Casper522

Reputation: 95

getting JSON data from PHP to iOS

I'am developing an iPhone application to display data from php. Data are obtained from a Mysql database then encoded to JSON format in php file:

include_once 'connectionIncl.php';

if(function_exists($_GET['method'])){
    $_GET['method']();

}
function getSQLIntoJSONFormat()
{
    $arr;
    $sql = mysql_query("SELECT * FROM pecivo");
    while($pecivo = mysql_fetch_assoc($sql)){
        $arr[] = $pecivo['typ'];
    }
    $arr= json_encode($arr);
    echo $_GET['jsoncallback'].'('.$arr.')';
}

// --- http://127.0.0.1:8887/TeplyRohlik/pecivo.php?method=getSQLIntoJSONFormat&jsoncallback=?

when i run this from browser, it returns correct data :

(["sejra","knir","baba","vousy","sporitelna25"])

Also, on iOS a have this code:

NSString * urlString = [NSString stringWithFormat:@"http://192.168.0.10:8887/TeplyRohlik/pecivo.php?method=getSQLIntoJSONFormat&jsoncallback=?"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"%@",json);

And result is .... (null). I have no idea how to get this working...

Upvotes: 1

Views: 3726

Answers (1)

mattjgalloway
mattjgalloway

Reputation: 34902

It looks like your PHP method is spitting out JSONP. What you probably want to do is change that to:

function getSQLIntoJSONFormat()
{
    $arr;
    $sql = mysql_query("SELECT * FROM pecivo");
    while($pecivo = mysql_fetch_assoc($sql)){
        $arr[] = $pecivo['typ'];
    }
    $arr= json_encode($arr);
    echo $arr;
}

You are seeing the output be wrapped in parentheses as it's expecting a GET parameter in the request called jsoncallback which would make the output look something like this:

javascriptFunction(["a","b","b"])

That's not what you want on your iOS device. You want just the raw JSON string of the array, no wrapping in a callback function call.

Upvotes: 2

Related Questions