Search code examples
iphoneiosjsonios6uipickerview

Access JSON file to populate UIPickerView


There's a similar question to this on this site but being that I cannot add another comment on that question in form of a question, I have chosen to write mine here, pardon me.Here goes,

I have a JSON file on a local server and trying to access the values on my UIPickerView. The problem is I get a "question mark, i.e "?" " instead of the strings on the JSON file. What's is the issue, how can i resolve this ? I'm still a beginner so go easy.

Here is the code,

#import "ViewController.h"
#import "JSON.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize picker;
@synthesize terrainJsonArray;

- (void)viewDidLoad
{
[super viewDidLoad];

NSString *terrainString = [NSString stringWithFormat:@"http://terrainracing.com/ios/events_json.php"];

NSURL *terrainUrl = [NSURL URLWithString:terrainString];

NSData  *terrainData = [NSData  dataWithContentsOfURL:terrainUrl];

NSError *error;

self.terrainJsonArray = [NSJSONSerialization JSONObjectWithData:terrainData options:kNilOptions error:&error];

NSLog(@"%@", terrainJsonArray);

}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView
 numberOfRowsInComponent:(NSInteger)component {
return self.terrainJsonArray.count;
}

#pragma mark Picker Delegate Methods
- (UIView *)pickerView:(UIPickerView *)pickerView
         titleForRow:(NSInteger)row
{

return [self.terrainJsonArray objectAtIndex:row];

}
@end

enter image description here


Solution

  • Start by fixing your delegate method - - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component returns NSString not UIView and you need to obviously return a string for it to work

    I can see in your response items as

    {"event_name":"Phoenix","date":"Oct 27","event_id":"14"}
    

    so you need to grab the string of "sub-item" you want to display

    for instance

    return [[self.terrainJsonArray objectAtIndex:row] valueForKey:@"event_name"];