Search code examples
jsonxcodeuipickerview

UIPickerView with JSON


I need help in retrieving a JSON object and parsing the array into my UIPickerView with 2 columns. One column is the data retrieve from JSON, the other column is hard coded. Is there any sample codes for parsing the JSON into the UIPickerView column?


Solution

  • I got you some code to get you started, but please keep in mind that: It is not optimized code (for example the call you make to fetch your data is executed in the main thread. In case you need to fetch large amounts of data you must make asynchronous calls). Its crucial to understand how the UIPickerView delegate & datasource is implemented. I hope that this will get you on the right track...

    // Get your JSON Data
    NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.mydomain.com/myjson.json"]];
    
    // Convert your JSON object to an 'NS' object
    NSError *error;
    id myJsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
    
    // Extract any data from your JSON object
    
    NSArray *myFirstArray = ...; // Your fixed array
    NSArray *mySecondArray = ...; // An array with data from your JSON
    
    
    // In your UIPIckerView datasource
    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
    {
        return 2;
    }
    
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
    {
        switch(component)
        {
            case 0:
                // First component
                return [myFirstArray count];
                break;
            case 1:
                // Second component
                return [mySecondArray count];
                break;
            default:
                return 0;
                break;
        }
    
        return 0;
    }
    
    
    // In your UIPIckerView delegate
    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
    {
        switch(component)
        {
            case 0:
                // First component
                return [myFirstArray objectAtIndex:row]; // We assume that you got NSString objects in the array
                break;
            case 1:
                // Second component
                return [mySecondArray objectAtIndex:row]; // We assume that you got NSString objects in the array
                break;
            default:
                return 0;
                break;
        }
    
        return @"";
    }