0

I'm looking to populate an array to be used in a pickerview. The data for the array is generated from a database table.

I have the following JSON_ENCODED array (created in php):

{"result":
 [
  {"id":"3","quivername":"Kite Boarding"},
  {"id":"4","quivername":"Live and Die in LA"},
  {"id":"14","quivername":"Bahamas Planning"},
  {"id":"15","quivername":"My Trip to India"},
  {"id":"16","quivername":"Snowboarding"}
 ]
}

UPDATE FOR WEBSERVICE PHP CODE

I run this function as a webservice:

passport($_SESSION['IdUser'])

function passport($userid) {

$result = query("SELECT id, quivername FROM quivers WHERE userid = $userid");

if (!$result['error']) {
    print json_encode($result);
} else {
        errorJson('Can not get passports');
    }
}

function query() {
global $link;
$debug = false;

//get the sql query
$args = func_get_args();
$sql = array_shift($args);

//secure the input
for ($i=0;$i<count($args);$i++) {
    $args[$i] = urldecode($args[$i]);
    $args[$i] = mysqli_real_escape_string($link, $args[$i]);
}

//build the final query
$sql = vsprintf($sql, $args);

if ($debug) print $sql;

//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {

    $rows = array();

    if ($result!==true)
    while ($d = mysqli_fetch_assoc($result)) {
        array_push($rows,$d);
    }

    //return json
    return array('result'=>$rows);

} else {

    //error
    return array('error'=>'Database error');
}
}

I USE THIS CODE IN XCODE TO CONNECT TO THE WEBSERVICE/WEBSITE USING NSNetworking...

-(void)getPassports {
    //just call the "passport" command from the web API
    [[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:
        @"passport",@"command",
        nil]
        onCompletion:^(NSDictionary *json) 
        {
        //got passports, now need to populate pickerArray1
        if (![json objectForKey:@"error"])
        {
                    //success, parse json data into array for UIPickerview
        } 
        else
        //error, no passports
        {
                    // error alert
        }

        }];
}

I need the following:

1) how can i populate an NSMutable array with the quivername value? I'm trying to get the result to look like this:

pickerArray1 = [[NSMutableArray alloc] initWithObjects:@"Kite Boarding",
@"Live and Die in LA", @"Bahamas Planning", @"My Trip to India", @"Snowboarding",
nil];

I'm assuming I need to run a for loop which would require me to "count" the number of rows in the array first, but I'm not sure. I don't know how to count the number of rows in the json_array or create an NSMutable array.

Thanks in advance...

1
  • How are you getting the PHP generated JSON into the iOS app? Can you provide more code? Commented Oct 11, 2012 at 18:27

2 Answers 2

1

You should be able to get your NSData from the URL that returns the JSON using [NSData dataWithContentsOfURL:yourURLValue], then pass the data and parse using something similar to what's below based on your JSON:

 //INVOKE WEB SERVICE QUERY IN VIEW DID LOAD -- RUNS ASYNC SO WONT BLOCK UI
- (void)viewDidLoad
{
    [super viewDidLoad];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData* data = [NSData dataWithContentsOfURL: 
          @"URLOFYOURWEBSERVICE"];  // <-- may need to cast string to NSURL....
        NSMutableArray *quivernames = [self performSelectorOnMainThread:@selector(fetchedData:) 
          withObject:data waitUntilDone:YES];
    });
}

- (NSMutableArray *)fetchedData:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    //ARRAY OR DICT DEPENDING ON YOUR DATA STRUCTURE
    NSDictionary* json = [NSJSONSerialization 
        JSONObjectWithData:responseData 

        options:kNilOptions 
        error:&error];
    //ITERATE AND/OR ADD OBJECTS TO YOUR NEW ARRAY
    NSMutableArray* JSONResultValues = [json objectForKey:@"yourKey"]; 
    NSMutableArray* resultValues = [[NSMutableArray alloc] init];
   for(int x = 0; x< [JSONResultValues count]; x++){
       NSDictionary *tempDictionary = [JSONResultValues objectAtIndex:x];
       [resultValues addObject:[tempDictionary objectForKey:@"quivername"]];
    }

    NSLog(@"Results Count: %@", [JSONResultValues count]);
   NSLog(@"Results Count: %@", [resultValues count]);
    return resultValues;
}

EDIT: For more info check out this explanation for JSON parsing http://www.raywenderlich.com/5492/working-with-json-in-ios-5

Sign up to request clarification or add additional context in comments.

4 Comments

Do I need to add code to iterate through the array? I updated my code, does this change your approach?
I'd put in your object for your key of result. It might be easier to create a second array of serviceResults; it looks like that should give you an array of data. for each item in that array i'd create a dictionary and store the object (NSString*) for key of quivername into the array serviceResults which then should give you an array of strings.
ok, so i added this code. should I replace "yourkey" with anything? Also, how do I call the function? Assuming in ViewDidLoad add: NSMutableArray* myData = [self fetchedData:responseData]; However, when I do this I get an error "use of undeclared identifier 'responseData'...
so, I only needed to do the following: replace "//success, parse json data into array for UIPickerview" with your code to iterate through the array. Everything else was unnecessary. So I marked it correct given that code...
0

You could try this (untested):

  //convert this to NSData, not sure how it is getting into obj-c
 {"result":[
  {"id":"3","quivername":"Kite Boarding"},
  {"id":"4","quivername":"Live and Die in LA"},
  {"id":"14","quivername":"Bahamas Planning"},
  {"id":"15","quivername":"My Trip to India"},
  {"id":"16","quivername":"Snowboarding"}
]};

NSMutableArray* myData = [self fetchedData:responseData]; 

- (NSMutableArray* )fetchedData:(NSData *)responseData {

    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization 

        JSONObjectWithData:responseData 

        options:kNilOptions 
        error:&error
    ];

    NSMutableArray* quivers = [json objectForKey:@"result"];

    return quivers;
 }

Wenderlich explains it here...

4 Comments

I just update the code to show how it's getting into the iphone, does that change the approach you described?
Nah, the method just takes json and converts it, it shouldn't matter how the json is getting in...
Assuming in ViewDidLoad add: NSMutableArray* myData = [self fetchedData:responseData]; However, when I do this I get an error "use of undeclared identifier 'responseData'...
The method is looking for you to pass NSData, not NSMutableArray

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.