UITableViewCell stored in other array - ios

I have one array(arrData) and UITableViewCell reload arrData. arrData stored in web service array of objects.
UITableViewCell in a two label and one image, label and image load data by arrData. so all label and image reload in same array but i want to reload different-different array each label and image.
ViewController
#import "ViewController.h"
#import "MemberTableViewCell.h"
#import "member_details.h"
#interface ViewController ()
{
NSArray *arrData;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.tabel_view setAllowsMultipleSelection:YES];
NSURLRequest *req=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:#"http://edutimeapp.com/toshow/chamber-of-commerc/ws/fetch_member.php"]];
response =[[NSMutableData alloc]init];
[NSURLConnection connectionWithRequest:req delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[response appendData:data];
NSLog(#"error receving data %#",response);
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSLog(#"Error in receiving data %#",error);
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"response data %#",json);
NSArray *status = json[#"status"];
arrData = status;
[self.tabel_view reloadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray<NSIndexPath *> *selectedRows = [tableView indexPathsForSelectedRows];
if (selectedRows && [selectedRows containsObject:indexPath]) {
return 127.0; // Expanded height
}
return 50.0; // Normal height
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arrData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MemberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ht"];
if (cell==nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.name.text= [[arrData objectAtIndex:indexPath.row] valueForKey:#"business_category_name"];
cell.title.text= [[[[arrData objectAtIndex:indexPath.row] valueForKey:#"business_details"] objectAtIndex:0] valueForKey:#"name"];
cell.email.text=[[[[arrData objectAtIndex:indexPath.row] valueForKey:#"business_details"] objectAtIndex:0] valueForKey:#"email"];
cell.image_view.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[[[arrData objectAtIndex:indexPath.row]valueForKey:#"business_details"]objectAtIndex:0] valueForKey:#"img_url"]]]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self updateTableView];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self updateTableView];
}
- (void)updateTableView
{
[self.tabel_view beginUpdates];
[self.tabel_view endUpdates];
}
#end

try this code
#import "ViewController.h"
#interface ViewController ()
{
IBOutlet UITableView *tbl;
NSMutableData *response;
NSMutableArray *Arrdata;
NSMutableArray *ArrySubData;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
Arrdata=[[NSMutableArray alloc]init];
ArrySubData=[[NSMutableArray alloc]init];
[tbl setAllowsMultipleSelection:YES];
NSURLRequest *req=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:#"http://edutimeapp.com/toshow/chamber-of-commerc/ws/fetch_member.php"]];
response =[[NSMutableData alloc]init];
[NSURLConnection connectionWithRequest:req delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[response appendData:data];
NSLog(#"error receving data %#",response);
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSLog(#"Error in receiving data %#",error);
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"response data %#",json);
NSArray *status = json[#"status"];
Arrdata = status;
NSLog(#"%#",Arrdata);
[tbl reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
ArrySubData=[[Arrdata objectAtIndex:section] objectForKey:#"business_details"];
return ArrySubData.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [NSString stringWithFormat:#" %#",[[Arrdata objectAtIndex:section] objectForKey:#"business_category_name"]];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 25;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UILabel *myLabel = [[UILabel alloc] init];
myLabel.frame = CGRectMake(0, 0, 320, 20);
myLabel.font = [UIFont fontWithName:#"Roboto-Bold" size:13.0];
myLabel.textColor=[UIColor whiteColor];
myLabel.backgroundColor=[UIColor colorWithRed:70.0/255.0 green:82.0/255.0 blue:88.0/255.0 alpha:1.0];
myLabel.text = [self tableView:tableView titleForHeaderInSection:section];
UIView *headerView = [[UIView alloc] init];
[headerView addSubview:myLabel];
return headerView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UIImageView *ImgBrands = (UIImageView *) [cell viewWithTag:101];
UILabel *lblName = (UILabel *) [cell viewWithTag:102];
UILabel *lblEmail = (UILabel *) [cell viewWithTag:103];
UILabel *lblPhone = (UILabel *) [cell viewWithTag:104];
ArrySubData=[[Arrdata objectAtIndex:indexPath.section] objectForKey:#"business_details"];
NSString *strName=[NSString stringWithFormat:#"%#",[[ArrySubData objectAtIndex:indexPath.row] objectForKey:#"name"]];
NSString *stremail=[NSString stringWithFormat:#"%#",[[ArrySubData objectAtIndex:indexPath.row] objectForKey:#"email"]];
NSString *strphone=[NSString stringWithFormat:#"%#",[[ArrySubData objectAtIndex:indexPath.row] objectForKey:#"phone"]];
NSString *strimage=[NSString stringWithFormat:#"%#",[[ArrySubData objectAtIndex:indexPath.row] objectForKey:#"image"]];
lblName.text=strName;
lblEmail.text=stremail;
lblPhone.text=strphone;
ImgBrands.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:strimage]]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self updateTableView];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self updateTableView];
}
- (void)updateTableView
{
[tbl beginUpdates];
[tbl endUpdates];
}

Related

How to handle two custom cells in one UITableView with UISegmentedControl Actions?

Hi i am new to iOS and SO also. i am facing a problem in my app to display the two custom cells in one tableview with selection of segmented control.when the user click on the segmented=0,it displays the one custom cell and segmented=1 display the second custom cell.
Here is my code upto now i tried,
-(void)callSegmentSelected
{
value1 = (int)segment.selectedSegmentIndex;
if (segment.selectedSegmentIndex == 0)
{
NSString *urlString = [NSString stringWithFormat:#"http:"url"];
NSString *jsonString = [NSString stringWithFormat:catid];
NSData *myJSONData =[jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:myJSONData]];
[request setHTTPBody:body];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
if(str.length > 0)
{
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
array =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
[myTableView reloadData];
}
else
{
NSLog(#"Error");
}
}
else if (segment.selectedSegmentIndex == 1)
{
}
Here is my tableview Delegate methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return array.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (value1 == 0)
{
static NSString *cellId = #"Cell";
Cell1 * cell = (Cell1 *)[myTableView dequeueReusableCellWithIdentifier:cellId];
if (cell == nil)
{
NSArray *myNib;
myNib = [[NSBundle mainBundle]loadNibNamed:#"Cell1" owner:self options:nil];
cell = [myNib lastObject];
}
cell.examLbl.text = [[array objectAtIndex:indexPath.row]objectForKey:#"examtitle"];
myTableView.dataSource = self;
myTableView.delegate = self;
[myTableView reloadData];
return cell;
}
else
{
if (value1 == 1)
{
static NSString * cellIdentifier = #"Cell2";
Cell2 *cell = (ContestRewardCell *)[myTableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
NSArray *myNib;
myNib = [[NSBundle mainBundle]loadNibNamed:#"cell2" owner:self options:nil];
cell =[myNib objectAtIndex:0];
}
cell.titleLbl.text = [[array objectAtIndex:indexPath.row]objectForKey:#"title"];
myTableView.dataSource = self;
myTableView.delegate = self;
[myTableView reloadData];
return cell;
}
}
return nil;
}
In this code there are no errors,i checked with debugging mode data will coming to "cell.examLbl.text",but not displaying the custom cell in tableview.What i did mistake in this Code Please help me any one.
Thanks in advance.
Here is answer for my problem, i am not implemented the this
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (value1 == 0)
{
return 102;
}
else if(value1 == 1)
{
return 193;
}
return 0;
}
you need to first register the cell nib in viewDid load
[YourTableView registerNib:[UINib nibWithNibName:#“YourCellNibName” bundle:nil] forCellReuseIdentifier:#“Identifier”];
then use the cell in cellForRowAtIndexPath
example:
-(void)viewDidLoad
{
[super viewDidLoad];
[TableView registerNib:[UINib nibWithNibName:#“MyTableViewCell” bundle:nil]forCellReuseIdentifier:#"cell"];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyTableViewCell *cell = (MyTableViewCell *)[myTableView dequeueReusableCellWithIdentifier:#"cell”];
cell.labelTitle=#"cell”;
return cell;
}

EXC_BAD_access code=1 address 0x NSURLConnection JSON

Doing JSON work in my iPhone app, trying to list the json in a tableview, the json can be found here: appwhittle.com/api/db_all.php
I need this json to work with both android and ios, since i made the android app first it works without problem on the android device, but i cant seem to figure out what is wrong.
SearchViewController.m:
//
// SearchViewController.m
// Night Locations
//
// Created by Stian Wiik Instebø on 12/9/13.
// Copyright (c) 2013 Stian Wiik Instebø. All rights reserved.
//
#import "SearchViewController.h"
#import "SBJson4.h"
#interface SearchViewController ()
#end
#implementation SearchViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title = #"Search for location";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"http://appwhittle.com/api/db_all.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData alloc] init];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
news = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[mainTableView reloadData];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"The download could not complete" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [news count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MainCell"];
}
[cell release];
cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"name"];
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
SearchViewController.h:
#import <UIKit/UIKit.h>
#interface SearchViewController : UIViewController {
IBOutlet UITableView *mainTableView;
NSArray *news;
NSMutableData *data;
}
#end
The error appears at the line: cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"name"]; where i get the title into one of the rows in the tableView.
What seems to be the problem, is it the formatting on the json? if it is, is there any way to get around it?
Programming for iOS 7
Any help is much appreciated!
Don't use these many lines use below code for it :
NSMutableURLRequest *request =[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:#"http://appwhittle.com/api/db_all.php"]];
NSData *returnData = [ NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
NSError *err = nil;
NSMutableArray *search = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
NSLog(#"Search %#",search);
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [search count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *store=#"cell";
UITableViewCell *utvc = [tableView dequeueReusableCellWithIdentifier:store];
if(utvc == nil)
{
utvc = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
}
NSString *str = [[[search valueForKey:#"locations"]objectAtIndex:indexPath.row]valueForKey:#"location"];
NSLog(#"%#", str);
return utvc;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
Try to use NSMutableArray for collecting data from connectionDidFinishLoading method.

Parse links of a JSON file und download them

I want to create an App which parses the picture Links of a Facebook page and shows them in an iOS app (display them in tableView). But after I parsed the JSON file and added them to an array which should be downloaded nothing is displayed.
Here's the code:
- (void)viewDidLoad
{
self.edgesForExtendedLayout = UIRectEdgeNone;
[super viewDidLoad];
items = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/HuppFotografie/photos/uploaded/?fields=id,name,picture"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
webData = [[NSMutableData alloc]init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"fail with error");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSArray *arrayOfData = [allDataDictionary objectForKey:#"data"];
for (NSDictionary *dicton in arrayOfData) {
NSString *picture = [dicton objectForKey:#"picture"];
[items addObject:picture];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 250.0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"MyImageCell";
ImageCell *cell = (ImageCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.backgroundColor = [UIColor clearColor];
if (cell == nil) {
NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"ImageCell" owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (ImageCell *)currentObject;
break;
}
}
}
// Here we use the new provided setImageWithURL: method to load the web image
[cell.imageView setImageWithURL:[NSURL URLWithString:[items objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:#"Placeholder.jpg"]];
cell.imageSource.text = [items objectAtIndex:indexPath.row];
return cell;
}
I really don't get why. I'm sorry if this question is stupid but I am coding just as a hobby and have not that great experience.
In fact your connection is asynchronous, so you just need to reload your table view programmatically to display loaded images:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSArray *arrayOfData = [allDataDictionary objectForKey:#"data"];
for (NSDictionary *dicton in arrayOfData) {
NSString *picture = [dicton objectForKey:#"picture"];
[items addObject:picture];
}
// Just add this line, in order to force reload when all your data is arrived
[self.tableView reloadData];
}

Parsing multiple jSon in IOS

For my code, I am following instruction on this link http://www.youtube.com/watch?v=RJZcD3hfs3k and success,
but I want to modify to multiple JSON and failed (if i print log, that its running).
I modify in:
- (void)viewDidLoad
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
This is my modified code(ViewController.m) :
#import "ViewController.h"
#import "DetailViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"News";
//[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//before
//NSURL *url = [NSURL URLWithString:#"http://zacandcatie.com/YouTube/json.php"];
//after
NSURL *url = [NSURL URLWithString:#"http://service.berisiknews.com/article/byAll/0/3"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//before
//news = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
//[mainTableView reloadData];
//ßNSLog(#"array %#", news);
//after
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: nil];
NSArray *news = [jsonArray valueForKeyPath:#"data"];
[mainTableView reloadData];
NSLog(#"array %#", news);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"The download could not complete please make sure you're connected to either 3G or Wi-Fi" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles: nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (int)numberINSectionsInTableView: (UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [news count];
//return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MainCell"];
}
cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"title"];
//cell.detailTextLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"date_string"];
cell.detailTextLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"category_name"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
detailViewController.title = [[news objectAtIndex:indexPath.row] objectForKey:#"title"];
detailViewController.newsArticle = [news objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailViewController animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Any help?
Your news array is a local variable as your code.
In connectionDidFinishLoading, please modify as below
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: nil];
news = [jsonArray valueForKeyPath:#"data"];
[mainTableView reloadData];
NSLog(#"array %#", news);
so it will be the right news array which your are accessing in table view.
it works fine for me.
#interface AlbumViewController ()
#end
#implementation AlbumViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//navigation Controller
[self.navigationController setNavigationBarHidden:NO];
self.title=#"Album List";
//json data parsing
NSURL *url = [NSURL URLWithString:#".......your Link......"];
NSURLRequest *urlrequest = [[NSURLRequest alloc]initWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:urlrequest returningResponse:nil error:nil];
dict_data = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.ary_data = [dict_data objectForKey:#"album"];
NSLog(#"%#",self.ary_data);
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [ary_data count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#""];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
NSMutableDictionary *dic= [[ary_data objectAtIndex:indexPath.row] mutableCopy];
AlbumCellController *albumCell = [[AlbumCellController alloc]init];
[cell.contentView addSubview:albumCell.view];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
albumCell.Img_album.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dic objectForKey:#"cover_photo"]]]];
});
albumCell.lbl_name.text = [dic objectForKey:#"title"];
albumCell.lbl_releasedate.text = [dic objectForKey:#"release_date"];
NSString *SongNo=[dic objectForKey:#"no_of_songs"];
NSLog(#"%#",SongNo);
//albumCell.lbl_songno.text=SongNo;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableDictionary *dic= [[ary_data objectAtIndex:indexPath.row] mutableCopy];
SongsViewController *songList = [[SongsViewController alloc]init];
songList.imgURL = [dic objectForKey:#"cover_photo"];
songList.Album_id = [dic objectForKey:#"album_id"];
[self.navigationController pushViewController:songList animated:YES];
}

Error Drawing JSOn into UITableviewCell

I have json like this (have dictionary and array).
I want draw all json into UItableviewcell, but its not draw there
{ data: [
{
featured: true,
price: {
currency: "IDR",
amount: 5557679,
formatted: "Rp5.558.000"
},
] }
and this is my viewcontroller.h file
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController{
IBOutlet UITableView *mainTableView;
NSURL *URL;
NSDictionary *Deals;
NSArray *Deals_array;
NSMutableData *data;
}
#end
and this is my .m file
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title=#"SOme Apps";
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
URL = [NSURL URLWithString:[NSString stringWithFormat:#"http://someurl.com"]];
NSURLRequest *request=[NSURLRequest requestWithURL:URL];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
/*dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: URL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});*/
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
data=[[NSMutableData alloc] init];
NSLog(#"%#",data);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSError* error;
Deals= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
Deals_array = [Deals objectForKey:#"data"]; //2
NSDictionary* loan = [Deals_array objectAtIndex:0];
NSString *test=[loan objectForKey:#"featured"];
NSLog(#"%#",test);
[mainTableView reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(#"Error");
}
////set minimum section oftableview
-(int)numberOfTableviewSection : (UITableView *) tableView
{
return 1;
}
////set length uitableview
-(int) tableView :(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [Deals_array count];
}
///declaring uitableview
-(UITableViewCell *)tableView :(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if (cell==nil){
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MainCell"];
}
cell.textLabel.text=[[Deals_array objectAtIndex:indexPath.row] objectForKey:#"featured"];
return cell;
}
#end
but its not draw the objectkey #test, can someone help me why?
Try doing the allocation
Deals_array = [[NSArray alloc] initWithArray:[Deals objectForKey:#"data"]];

Resources