0

I followed Ray Wenderlich's tutorial on creating a web service / hooking it up to iOS but his example the returned results only have one possible row returned in the query. I'd like to return all possible results in a JSON format but I am confused how to store them as the correct key.

Here's what I have for the PHP:

$stmt = $this->db->prepare('SELECT userID, lat, lng FROM Connections WHERE airline=? AND flight_number=? ');
$stmt->bind_param("si", $airline, $flight_number);
$stmt->execute();
$stmt->bind_result($otherUser, $otherLat, $otherLng);
    while ($stmt->fetch()) {
        break;
    }
 $stmt->close();

if ($otherUser) {
        //sendResponse(403, 'Code already used');
        //return false;
        $myLatLng = "$lat,$long";
        $otherLatLng="$otherLat,$otherLng";
        $results = getDistanceBetween($myLatLng,$otherLatLng);
        $miles = $results[0];
        $minutes = $results[1];
        $result = array(
                "other_user" => $otherUser,
                "distance" => $miles,
                "duration" => $minutes,

                );
        sendResponse(200, json_encode($result));
        return true;
    }

On the Obj-C side of things I get these values using this code:

 if (request.responseStatusCode == 200) {
    NSString *responseString = [request responseString];
    NSDictionary *responseDict = [responseString JSONValue];
    NSString *otherUser = [responseDict objectForKey:@"other_user"];
    NSString *otherDistance = [responseDict objectForKey:@"distance"];
    NSString *otherDuration = [responseDict objectForKey:@"duration"];

Can someone please help me out?

mkral
  • 4,065
  • 4
  • 28
  • 53

1 Answers1

1

In your PHP code you want to create a nested array and then use json_encode(). Here is a previous question with more detail about the PHP side of your problem: How to create an array for JSON using PHP?

On the iOS side, since your webservice will return a JSON response representing multiple items, calling JSONValue on the response string will return an NSArray object instead of an NSDictionary. You can then iterate over the items in the array (which will themselves be NSDictionary items) and pull out the values you need.

NSString *responseString = [request responseString];
NSArray *responseArray = [responseString JSONValue];

for (NSDictionary* item in responseArray) {
    NSString *otherUser = [item objectForKey:@"other_user"];
    NSString *otherDistance = [item objectForKey:@"distance"];
    NSString *otherDuration = [item objectForKey:@"duration"];
}
Community
  • 1
  • 1
jonkroll
  • 15,682
  • 4
  • 50
  • 43
  • Thanks for this but do you know how I can return the array in JSON format? I'm confused with the PHP/SQL/JSON part but I didn't even consider the iOS Array part – mkral Feb 22 '12 at 23:57