json from photos UITableView in not show - ios

My question:
in json can not properly address the image. Each line corresponds to the incorrect image is coming. Comes in 3 different sizes. How to parse them TableView 's imageviewer' How do I dispose of. Thank you.
ScreenShot:
My code:
#import "TableViewController.h"
#interface TableViewController (){
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *labelArray;
NSMutableArray *imageArray;
}
#end
#implementation TableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *removeAllData = [NSMutableArray arrayWithObjects:imageArray,labelArray,nil];
[removeAllData removeAllObjects];
[self.tableView setDelegate:self];
[self.tableView setDataSource:self];
labelArray = [[NSMutableArray alloc]init];
imageArray = [[NSMutableArray alloc]init];
NSString *strURL = #"https://itunes.apple.com/tr/rss/newapplications/limit=25/json";
NSURL *url = [NSURL URLWithString:strURL];
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(#"Error");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:kNilOptions error:nil];
NSDictionary *allFeedDictionary = [allDataDictionary objectForKey:#"feed"];
NSArray *arrayOfEntry = [allFeedDictionary objectForKey:#"entry"];
for (NSDictionary *diction in arrayOfEntry) {
NSDictionary *title = [diction objectForKey:#"title"];
NSDictionary *imImage = [diction objectForKey:#"im:image"];
for (NSDictionary *imageDict in imImage) {
NSDictionary *imageLabel = [imageDict objectForKey:#"label"];
[imageArray addObject:imageLabel];
}
NSString *label = [title objectForKey:#"label"];
[labelArray addObject:label];
}
[self.tableView reloadData];
NSLog(#"%#",[imageArray objectAtIndex:0]);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return labelArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
//NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: [imageArray objectAtIndex:indexPath.row]]];
NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:[imageArray objectAtIndex:indexPath.row]]];
UIImage *image = [[UIImage alloc] initWithData:imageData];
cell.textLabel.text = [labelArray objectAtIndex:indexPath.row];
cell.imageView.image = image;
return cell;
}

for (NSDictionary *imageDict in imImage) {
NSDictionary *imageLabel = [imageDict objectForKey:#"label"];
[imageArray addObject:imageLabel];
break;
}
OR
[imageArray addObject: imImage[0][#"label"]];
Just replace this in your code. You need to break the loop as your required size image always lies at 0th index.

Related

How to print a phone number of a Contacts in table cell

Check my Code:
#import "ContactViewController.h"
#import "SimpleTableCell.h"
#import Contacts;
#import ContactsUI;
#interface ContactViewController ()
#end
#implementation ContactViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
_Contacts = [[NSMutableArray alloc]init];
_fullName = [[NSMutableArray alloc]init];
_phone = [[NSMutableArray alloc]init];
[self fetchContacts];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void) fetchContacts
{
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES) {
//keys with fetching properties
NSArray *keys = #[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSError *error;
NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
if (error) {
NSLog(#"error fetching contacts %#", error);
} else {
NSString *phone;
NSString *fullName;
NSString *firstName;
NSString *lastName;
UIImage *profileImage;
NSMutableArray *contactNumbersArray;
for (CNContact *contact in cnContacts) {
// copy data to my custom Contacts class.
firstName = contact.givenName;
lastName = contact.familyName;
if (lastName == nil) {
fullName=[NSString stringWithFormat:#"%#",firstName];
}else if (firstName == nil){
fullName=[NSString stringWithFormat:#"%#",lastName];
}else{
fullName=[NSString stringWithFormat:#"%# %#",firstName,lastName];
}
UIImage *image = [UIImage imageWithData:contact.imageData];
if (image != nil) {
profileImage = image;
}else{
profileImage = [UIImage imageNamed:#"acc_sett.png "];
}
for (CNLabeledValue *label in contact.phoneNumbers) {
phone = [label.value stringValue];
if ([phone length] > 0) {
NSMutableArray *cleanArray = [[NSMutableArray alloc] initWithCapacity:0];
// Here 'Activity' is your NSArray. A better name would be 'activity'
// (save capitalized names for classes)
for (NSString *item in contactNumbersArray)
{
[cleanArray addObject:[[item componentsSeparatedByString:#"-"] lastObject]];
}
NSLog(#"%#",cleanArray);
[contactNumbersArray addObject:phone];
}
}
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,#"fullName",profileImage, nil];
[_Contacts addObject:personDict];
NSLog(#"%#",phone);
NSLog(#"%#",fullName);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.contacttableview reloadData];
});
}
}
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [_Contacts count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary* personDict = [_Contacts objectAtIndex:indexPath.row];
static NSString *simpleTableIdentifier = #"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.Name.text = [personDict objectForKey:#"fullName"];
cell.Phone.text = [personDict objectForKey:#"phoneNumbers"];
cell.thumbnailImageView.image = [personDict objectForKey:#"userImage"];
NSData *dataItems=UIImageJPEGRepresentation(cell.thumbnailImageView.image, 0.1);
NSString *mysavedimage=#"userImage";
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *DocumentDirectry=[path objectAtIndex:0];
NSString *fullpathfile=[DocumentDirectry stringByAppendingPathComponent:mysavedimage];
[dataItems writeToFile:fullpathfile atomically:YES];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier:#"showDetail" sender:self];
}
#end
With the help of this code fullname and image of contacts person is coming on Table view but the Phone number is not coming and I am using a Custom Cell for the display of and one thing after fetching contacts from the simulator in console phone number and full name is both coming on console but on Table View Phone number is not coming.
May be I'm wrong somewhere. Please help, thank you in advance.
Try this:
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,#"fullName", phone,#"phoneNumbers",profileImage,#"userImage" nil];
instead of:
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,#"fullName",profileImage, nil];
You are not updating the dictionary with required data.

how to display the key to the tableview

how to display the key on tableview at the same time?
Here I can display the value.
I want to show the key on cell.textLabel setText:#"A"
Please..
.
.
.
Here is my code
ThankYou
Thankyou very much.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://reserve.cdn-apple.com/AU/en_AU/reserve/iPhone/availability.json"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
_listarr = [[NSMutableArray alloc]init];
id list = [dic objectForKey:self.strStore];
if ([list isKindOfClass:[NSDictionary class]]) {
NSDictionary *dictionary = (NSDictionary *)list;
NSArray *keys = [list allKeys];
for (NSString *key in keys) {
NSString *teamname = (NSString *)[dictionary objectForKey:key];
NSLog(#"",key);
[_listarr addObject:[NSString stringWithFormat:#"%#", teamname]];
}
} else {
// Do some error handling
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//必须返回与数据容器一样的数量,否则会报数据越界错
return [_listarr count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"thisCell";
UITableViewCell *cell;
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
[cell.textLabel setText:#"A"];
[cell.detailTextLabel setText:[_listarr objectAtIndex:indexPath.row]];
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
#end
Hi this code will give you what you required I think..
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSArray *array = [dic allKeys];
NSArray *temparray = [dic objectsForKeys:array notFoundMarker:[NSNull null]];
Use NSDictionary's allKeysForObject: to look up keys that match an object. Objects are compared with isEqual: and should match for simple NSStrings.
If the array is too large, this may be slow, in which case you might create another array with the key values that you can index quickly.

how to parsing data in JSON to tableview

I have a json http://vmg.hdvietpro.com/ztv/home and how to parsing data json in this link to table view. I try this code but i cant get data from json to my application.Thanks for help
Movies.h
#interface Movies : NSObject
#property (strong,nonatomic) NSString *moviesId;
#property (strong,nonatomic) NSString *text1;
#property (strong,nonatomic) NSString *thumbnail;
#pragma mark -
#pragma mark Class Methods
-(id)initWithMoviesName:(NSString *)cText1 andThumbnail:(NSString*) cThum andMoviesID:(NSString*) cID;
#end
Movies.m
#implementation Movies
#synthesize text1,moviesId,thumbnail;
-(id)initWithMoviesName:(NSString *)cText1 andThumbnail:(NSString*) cThum andMoviesID:(NSString *) cID{
self=[super init];
if (self) {
text1=cText1;
thumbnail=cThum;
moviesId=cID;
}
return self;
}
#end
TableViewController
#define getDataURL #"http://vmg.hdvietpro.com/ztv/home"
-(void) retrieveData{
NSURL *url=[NSURL URLWithString:getDataURL];
NSData *data=[NSData dataWithContentsOfURL:url];
jsonArray=[NSJSONSerialization JSONObjectWithData:data
options:kNilOptions error:nil];
moviesArray=[[NSMutableArray alloc] init];
for (int i=0; i<jsonArray.count; i++) {
NSString *cID=[[jsonArray objectAtIndex:i] objectForKey:#"id"];
NSString *cName=[[jsonArray objectAtIndex:i] objectForKey:#"text1"];
NSString *cThum=[[jsonArray objectAtIndex:i] objectForKey:#"thumbnail"];
[moviesArray addObject:[[Movies alloc]initWithMoviesName:cName andThumbnail:cThum andMoviesID:cID]];
}
[self.tableView reloadData];
}
Try Following:
NSArray * respArray = [[[[json objectForKey:#"response"]objectForKey:#"hot_program"]objectForKey:#"itemPage"]objectForKey:#"page"];
Try doing something like this. This is not the exact solution and you'll have to work around your way.
NSString *link = [NSString stringWithFormat:#"yourServiceURL"];
NSString *encdLink = [link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:encdLink];
NSData *response = [NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response options: NSJSONReadingMutableContainers error: &error];
Now you have your data in the array and extract it out using objectForKey or valueForKey.
This is what I am doing to fetch images from JSON and showing in my app. Firstly get the array from the above code. Then extract out the image content like this :
_demoArray = [json valueForKey:#"ContentImage"];
Now you have the values in your demoArray.
Hope this helps.
I thing it's useful for you.try this way
#import "ViewController.h"
#interface ViewController ()
{
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *array;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[self TableView]setDataSource:self];
array=[[NSMutableArray alloc]init];
NSURL *url=[NSURL URLWithString:#"https://itunes.apple.com/us/rss/topaudiobooks/limit=10/json"];
NSLog(#"https://itunes.apple.com/us/rss/topaudiobooks/limit=10/json");
NSURLRequest *req=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:req delegate:self];
if(connection)
{
NSLog(#"Connected");
webData=[[NSMutableData alloc]init];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(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(#"Error is");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *all=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
// NSString *label=[all objectForKey:#"lable" ];
// [array addObject:label];
NSDictionary *feed=[all objectForKey:#"feed"];
NSArray *arrayOFEntry=[feed objectForKey:#"entry"];
for (NSDictionary *diction in arrayOFEntry) {
NSDictionary *title=[diction objectForKey:#"title"];
NSString *label=[title objectForKey:#"label"];
[array addObject:label];
}NSLog(#"good mrng");
[[self TableView]reloadData];
}
- (IBAction)getTopMoves:(id)sender
{
NSLog(#"good mrng");
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
return cell;
}
#end
try this...
-(void) retrieveData1
{
NSURL * url = [NSURL URLWithString:getDataURL1];
NSData * data = [NSData dataWithContentsOfURL:url];
id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
_moviesArray=[[NSMutableArray alloc] init];
_moviesArray1=[[NSMutableArray alloc] init];
_moviesArray2=[[NSMutableArray alloc] init];
// NSArray * respArray = [[[[json objectForKey:#"response"]objectForKey:#"hot_program"]objectForKey:#"itemPage"]objectForKey:#"page"];
NSDictionary *dic=[json objectForKey:#"response"];
NSDictionary *dic1= [dic objectForKey:#"hot_program"];
NSDictionary *dic2=[dic1 objectForKey:#"itemPage"];
for (NSDictionary *diccc in [dic2 objectForKey:#"page"])
{
NSLog(#"%#",diccc);
[self.moviesArray addObject:[diccc objectForKey:#"id"]];
[self.moviesArray1 addObject:[diccc objectForKey:#"text1"]];
[self.moviesArray2 addObject:[diccc objectForKey:#"thumbnail"]];
}
NSLog(#"%#",self.moviesArray);
NSLog(#"%#",self.moviesArray1);
NSLog(#"%#",self.moviesArray2);
// [self.tableView reloadData];
}
it is one of way to parse a data there is lot of way to parse..
NSArray * respArray = [[[[json objectForKey:#"response"]objectForKey:#"hot_program"]objectForKey:#"itemPage"]objectForKey:#"page"];
NSLog(#"%#",respArray);
NSArray *respArray1= [[[[json objectForKey:#"response"]objectForKey:#"new_video"]objectForKey:#"itemPage"]objectForKey:#"page"];;
NSLog(#"%#",respArray1);
NSArray *respArray2= [[json objectForKey:#"response"]objectForKey:#"hot_program_by_category"];
NSLog(#"%#",respArray2);
for (NSDictionary *dic in [[respArray2 valueForKey:#"itemPage"]valueForKey:#"page"])
{
NSLog(#"%#",dic);
}
and don't forget to reload a tableview..i commented there just uncomment it

Cell text overlapping when scrolling in UITableView Xcode iOS

Everytime I start scrolling in the tableView the subtitleLabel text keeps overlapping each other in every row. I've tried for the last 4 hours every single search on the Internet for this problem I have clicked and tried.
Here is my ViewController.m:
#interface ANViewController()
{
NSMutableArray *TitleLabel;
NSMutableArray *SubtitleLabel;
NSMutableArray *AvatarImages;
}
#end
#implementation ANViewController
#synthesize thetableview;
- (void)viewDidLoad
{
[super viewDidLoad];
self.thetableview.delegate = self;
self.thetableview.dataSource = self;
TitleLabel = [NSMutableArray array];
SubtitleLabel = [NSMutableArray array];
AvatarImages = [NSMutableArray array];
__block NSArray *posts;
__block NSData *allNewsData = nil;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0ul);
dispatch_async(queue, ^{
allNewsData = [NSData dataWithContentsOfURL:[NSURL URLWithString: API_URL]];
NSError *error;
NSMutableDictionary *allNews = [NSJSONSerialization JSONObjectWithData:allNewsData options:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
posts = allNews[#"data"];
for (NSDictionary *newsPost in posts) {
[TitleLabel addObject:newsPost[#"title"]];
[SubtitleLabel addObject:newsPost[#"post_message"]];
NSString *avatarUrl = AVATAR_URL;
NSString *avatarExt = #".jpg";
[AvatarImages addObject:[NSString stringWithFormat:#"%#%#%#", avatarUrl, newsPost[#"user_id"], avatarExt]];
}
}
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"THIS IS THE MAIN THREAD...");
[self.thetableview reloadData];
});
});
NSURL *url = [NSURL URLWithString: WEBSITE_URL];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
long count = TitleLabel.count;
if(count == 0){
count = 1;
}
return count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier;
ANTableViewCell *Cell;
if(TitleLabel.count == 0){
NSLog(#"Did with no news");
CellIdentifier = #"Cell_NoNews";
Cell = [thetableview dequeueReusableCellWithIdentifier:CellIdentifier];
if (Cell == nil) {
Cell = [[ANTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.noNewsLabel.text = #"No news to display!";
}else{
NSLog(#"Did with news");
CellIdentifier = #"Cell";
Cell = [thetableview dequeueReusableCellWithIdentifier:CellIdentifier];
if (Cell == nil) {
Cell = [[ANTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.TitleLabel.text = [TitleLabel objectAtIndex:indexPath.row];
Cell.SubtitleLabel.text = [SubtitleLabel objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:[AvatarImages objectAtIndex:indexPath.row]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
Cell.AvatarImage.image = img;
}
return Cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
Just change UITableViewCellStyleSubtitle for UITableViewCellStyleDefault, and you need an asynchronous connection instead of a synchronous like you're doing: NSData *allNewsData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:API_URL]]; in your viewDidLoad method that is blocking your main thread.
You can adapt this code to your need, in order to download it on the background:
__block NSData *allNewsData = nil;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
allNewsData = [NSData dataWithContentsOfURL:[NSURL URLWithString: API_URL]];
NSURL *url = [NSURL URLWithString: WEBSITE_URL];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"THIS IS THE MAIN THREAD...");
[self.thetableview reloadData];
});
});

Bind existing Array to tableView IOS

i have an array that contains 5 items when i debugging but when i try to bind them to a tableview the tableview is empty without error.
It works if a do an array manually and initwithobjects but i already have an array.
After this my array have 5 objects
array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
The problem is the part where i try to init the array.
If i do this my array is null after.
array = [[NSMutableArray alloc] init];
and if i do this my array still have 5 object but not loaded into table
array = [array init];
Thanks for your help
All Code
NSArray *array;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *request = [NSString stringWithFormat:
#"http://192.168.99.99/IBookService.svc/GetBooksNames"];
NSURL *URL = [NSURL URLWithString:
[request stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:URL options:NSDataReadingUncached error:&error];
if(!error)
{
array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
array = [[NSMutableArray alloc] init];
}
_tblCustomers.dataSource = self;
_tblCustomers.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identity = #"custTbl";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identity];
if (cell==nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:identity];
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
}
You add object to the array and after that you allocate it (clear it). Do it other way around:
if(!error)
{
array = [[NSMutableArray alloc] init];
array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
}
Currently array is deallocated when you leave viewDidLoad method. You should make array a member of class to avoid this. For example you can add following
{
NSArray *array;
}
after line
#implementation Your_class_name_here
And delete your current line
NSArray *array;

Resources