Search This Blog

Tuesday, 21 August 2012

How to use JSON in xcode

Hello Friends,
                  Here is the simple twitter example to fetch public tweet from  a url which is providing data n JSON Format .

CODE:

fetchedData is a function i am using to fetch the data from twitter URL and saving it in a NSArray tweets:


-(void)fetchTweets{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://api.twitter.com/1/statuses/public_timeline.json"]];
        NSError *error;
        if(data!=nil){
        tweets = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if(data!=nil){
            [self.tableView reloadData];
            }else{
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Request Limit Reached." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }
            });
    });
}


Now below i am fetching the data by defining keys for object and using it as a cell text:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"TweetCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(cell==nil){
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
    NSString *text =[tweet objectForKey:@"text"];
    NSString *name = [[tweet objectForKey:@"user"]objectForKey:@"name"];
    
    cell.textLabel.text = text;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"by %@",name];
    return cell;
}


How to use this:

Just call fetcheddata method in your viewDidLoad method , it will fetch the data from url and JSONSerialization will serialize it and save it in an Array.

Next what we are doing in cellForRowAtIndexPath is , we are fetching the values for particular keys from the Array in which we have saved the Data in a serialized form and finally we are using that data in different ways....


Ask for any queries....

No comments:

Post a Comment