Can't reload data in tableView after parsing XML - ios

I'm starting NSURLConnection, parsing XML, initialize array from this XML, and show it in the tableView. In connectionDidFinishLoading I'm trying [self.tableView reloadData, but it doesn't work. This is my code:
my .h file:
#interface catalogViewController : UITableViewController //
#property (nonatomic, strong) NSMutableData *receivedData;
#property (nonatomic,retain) NSArray * titleArr;
#property (nonatomic,retain) NSArray * contentArr;
#property (nonatomic,retain) NSArray * ImageURLArr;
#property (nonatomic,retain) NSArray * dateArr;
#property (nonatomic,retain) NSArray * priceArr;
#property (nonatomic,retain) NSDictionary * xmlDictionary;
#property (nonatomic,retain) NSArray * IDArr;
#property (nonatomic) BOOL * didDataLoaded;
#property (strong, nonatomic) IBOutlet UITableView *myTableView;
#end
My .m file:
#import "catalogViewController.h"
#import "XMLReader.h"
#interface catalogViewController ()
#end
#implementation catalogViewController
- (id)initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self) { } return self;
}
//-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-CONNECTIONS METHOD START-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
[_receivedData release];
NSString *errorString = [[NSString alloc] initWithFormat:#"Connection failed! Error - %# %# %#", [error localizedDescription], [error description], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]]; NSLog(#"%#",errorString);
[errorString release];
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-GET FULL DATA HERE-=-=-=-=-=-=-=-=--=-=-=-=-=-=-
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *dataString = [[NSString alloc] initWithData:_receivedData encoding:NSUTF8StringEncoding];
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART START-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //
NSString *testXMLString = [NSString stringWithContentsOfURL:myURL usedEncoding:nil error:nil];
// -=-=-=-=-=-=-=-=-=-=Parse the XML into a dictionary-=-=-=-=-=-=-=-=-=-=
NSError *parseError = nil;
_xmlDictionary = [XMLReader dictionaryForXMLString:testXMLString error:&parseError];
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART END-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
_titleArr =[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"name"] valueForKey:#"text"];
_IDArr =[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"id"] valueForKey:#"text"];
_priceArr=[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"price"] valueForKey:#"text"];
_ImageURLArr=[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"img"] valueForKey:#"text"];
[connection release];
[_receivedData release];
[dataString release];
_didDataLoaded=TRUE;
[_myTableView reloadData]; // IBOutlet property
[self.tableView reloadData]; //default
}
//-=-=-=-=-=-=-=-=-=-=-Connection methods END-=-=-=-=-=-=-=-=-=-
- (void)viewDidLoad {
[super viewDidLoad];
_didDataLoaded=FALSE;
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART START-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//-=-==-=-=-=-=-=-=-=-=-=-=--=-=START Shit with connection-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=
NSString* params = #"request_params";
NSURL* url = [NSURL URLWithString:#"my URL"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
request.HTTPMethod = #"POST";
request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
NSLog(#"Connecting...");
_receivedData = [[NSMutableData data] retain];
} else {
NSLog(#"Connecting error");
}
}
//-=-==-=-=--=-==-=-=-=-=-=--=-==---=-=--==-=-=-=-=-TableView methods-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=--=-=-=-=-=-=-=
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (_didDataLoaded == FALSE) {
return 1;
}
else return self.titleArr.count;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { return 1; }
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"creatures"];
UIImage *creatureImage = nil;
if (_didDataLoaded == FALSE) {
cell.textLabel.text=#"Downloading...";
cell.detailTextLabel.text= #"downloading...";
} else {
cell.textLabel.text = [self.titleArr objectAtIndex:indexPath.row];
cell.detailTextLabel.text= _IDArr[indexPath.row];
NSString *img = self.ImageURLArr[indexPath.row];
creatureImage =[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:img]]]; cell.imageView.image = creatureImage;
}
return cell;
}
#end
XML downloading - OK, parsing - OK, initialising arrays - OK. But when I start project I have exception on the line NSLog(#"%#", self.titleArr objectAtIndex:indexPath.row]; - says: "Thread 1: EXC_BAD_ACCESS (code 1)
How can I understand it's means that it's trying initialize array when it's not prepare. My problem is i can't delay tableView methods or what? How can i fix it? I'm trying fix itfor some days...

Your titleArr is deallocated from memory and then you are requesting object of it so it is giving you a crash. So allocate memory to array by this way.
_titleArr = [[NSArray alloc] initWithArray:[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"name"] valueForKey:#"text"]];

Eventhough it's not recommended way but the following can provide a solution to you
self.tableView.delegate = nil;
self.tableView.datasource = nil;
and when safely your array was populated with the xml data set back to
self.tableView.delegate = self;
self.tableView.datasource = self;

Related

Search results are not showing

I am new in iOS developing. In my project I have taken a tableView and a search bar. Now when I am searching one of the datas of my tableview, no search results are coming. Can anyone please solve my problem?
Any help will be appreciated. Thanks in advance.
This is my ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property(strong, nonatomic) NSMutableData *postData;
#property(nonatomic, strong)NSArray *arrDetail;
#property(nonatomic, strong)NSArray *searchResults;
#property (weak, nonatomic) IBOutlet UITableView *parserTable;
#property (strong, nonatomic) IBOutlet UIActivityIndicatorView *mySpinner;
#end
This is my ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_mySpinner.hidden = NO;
[self fetchData];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (BOOL)prefersStatusBarHidden {
return YES;
}
- (void) fetchData {
[_mySpinner startAnimating];
NSString *post = [NSString stringWithFormat:#"test=Message&this=isNotReal"];
_postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [_postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://svn.indusnettechnologies.com/HHC/webservice/users/countrylist?apiKey=hgfyhfyi87hgc67"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:_postData];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
_postData = [NSMutableData data];
}
else{
//error
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_postData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
// self.data parse
NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:self.postData options:kNilOptions error:nil];
self.arrDetail = [dict valueForKey:#"Countries"];
[self.mySpinner stopAnimating];
self.mySpinner.hidden = YES;
[self.parserTable reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
}
#pragma mark Table View Delegates
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"tableCell"];
UILabel *lbl1 = (UILabel*)[cell.contentView viewWithTag:2];
lbl1.text = [[self.arrDetail objectAtIndex:indexPath.row]valueForKey:#"CountryCode"];
UILabel *lbl2 = (UILabel*)[cell.contentView viewWithTag:1];
lbl2.text = [[self.arrDetail objectAtIndex:indexPath.row]valueForKey:#"CountryName"];
UILabel *lbl3 = (UILabel*)[cell.contentView viewWithTag:3];
lbl3.text = [NSString stringWithFormat:#"%d.", indexPath.row];
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//return [self.arrDetail count];
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [_searchResults count];
} else {
return [_arrDetail count];
}
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"SELF contains[cd] %#",
searchText];
_searchResults = [_arrDetail filteredArrayUsingPredicate:resultPredicate];
}
#pragma mark - UISearchDisplayController delegate methods
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Change following method like I have done:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"tableCell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSMutableDictionary * tempDict;
if (tableView == self.searchDisplayController.searchResultsTableView)
{
tempDict = [_searchResults objectAtIndex:indexPath.row];
}
else
{
tempDict = [_arrDetail objectAtIndex:indexPath.row];
}
UILabel *lbl1 = (UILabel*)[cell.contentView viewWithTag:2];
lbl1.text = [tempDict valueForKey:#"CountryCode"];
UILabel *lbl2 = (UILabel*)[cell.contentView viewWithTag:1];
lbl2.text = [tempDict valueForKey:#"CountryName"];
UILabel *lbl3 = (UILabel*)[cell.contentView viewWithTag:3];
lbl3.text = [NSString stringWithFormat:#"%d.", indexPath.row];
return cell;
}
Problem is also in your predicate. change it
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
//country_name and country_code are keys in your dictionary of country
NSPredicate *p1 = [NSPredicate predicateWithFormat:#"country_name contains[cd] %#", searchText];
NSPredicate *p2 = [NSPredicate predicateWithFormat:#"country_code contains[cd] %#", searchText];
NSPredicate *resultPredicate = [NSCompoundPredicate orPredicateWithSubpredicates: #[p1, p2]];
_searchResults = [_arrDetail filteredArrayUsingPredicate:resultPredicate];
}

Google Translate API on iPhone

I am writing a simple code, in which I am using Google API for translation services, but I am getting the following error:
Connection failed: Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x176c80a0 {NSUnderlyingError=0x175c8d00 "bad URL", NSLocalizedDescription=bad URL}
This is the code I have written:
#import "ViewController.h"
#import"SBJson.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet UITextField *textfield;
#property (strong, nonatomic) IBOutlet UIButton *go;
#property (strong, nonatomic) IBOutlet UITextView *textview;
- (IBAction)translate:(id)sender;
#property (strong, nonatomic) NSMutableArray *translations;
#property (strong, nonatomic)NSString *_lastText;
#property (nonatomic, copy) NSString * lastText;
#end
#implementation ViewController
#synthesize lastText = _lastText;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//Initializing the translation array
_translations = [[NSMutableArray alloc] init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)performTranslation {
responseData = [[NSMutableData data] init ];
NSString *langString = #"en|ja";
NSString *textEscaped = [_lastText
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *langStringEscaped = [langString
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//My_Key=Google generated key
NSString *url = [NSString stringWithFormat:#"https://www.googleapis.com/language/translate/v2?
key={My_key}&source=en&target=de&q=%#",textEscaped];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (IBAction)translate:(id)sender {
[_translations removeAllObjects];
[_textfield resignFirstResponder];
_go.enabled=NO;
self.lastText = _textfield.text;
[_translations addObject:_lastText];
_textview.text = _lastText;
[self performTranslation];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
_textview.text = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
_go.enabled = YES;
NSLog([NSString stringWithFormat:#"Connection failed: %#", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
NSMutableDictionary *luckyNumbers = [responseString JSONValue];
if (luckyNumbers != nil) {
NSDecimalNumber * responseStatus = [luckyNumbers objectForKey:#"responseStatus"];
if ([responseStatus intValue] != 200) {
_go.enabled = YES;
return;
}
NSMutableDictionary *responseDataDict = [luckyNumbers objectForKey:#"responseData"];
if (responseDataDict != nil) {
NSString *translatedText = [responseDataDict objectForKey:#"translatedText"];
[_translations addObject:translatedText];
self.lastText = translatedText;
_textview.text = [_textview.text stringByAppendingFormat:#"\n%#", translatedText];
_go.enabled = YES;
}
}
}
#end
The problem is like it says. The URL has been generated incorrectly. Try:
NSString * source = #"en";
NSString * target = #"ja";
NSString * key = #"YOUR-KEY";
NSString * url = [NSString stringWithFormat:#"https://www.googleapis.com/language/translate/v2?key=%#&source=%#&target=%#",key,source,target];
and see what response you get.
You can just use FGTranslator. Simple.
FGTranslator *translator = [[FGTranslator alloc] initWithGoogleAPIKey:#"your_google_key"];
[translator translateText:#"Bonjour!"
completion:^(NSError *error, NSString *translated, NSString *sourceLanguage)
{
if (error)
NSLog(#"translation failed with error: %#", error);
else
NSLog(#"translated from %#: %#", sourceLanguage, translated);
}];

How to reloadData in tableView with didSelectedRowAtIndexPath and call group of methods in it

In my app I'm starting NSURLConnection, parsing XML, initialize array from this XML, and show it in the tableView. In ViewDidLoad I appeal to the server with a query parameter 0 , and it's returned for me string, after all conversion a have in tableView 4 rows - titles, and when i push on some of this titles, all process (connection to the server, parsing, arrays initialising, ) must be repeated. In didSelectedRowAtIndexPath I have to transmit section ID (so that the server sent me the correct data). How can I do it correctly? I'm establish connection in ViewDidLoad, how can I call it again?
My .m file:
#import "catalogViewController.h"
#import "XMLReader.h"
#interface catalogViewController ()
#end
#implementation catalogViewController
- (id)initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self) { } return self;
}
//-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-CONNECTIONS METHOD START-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
[_receivedData release];
NSString *errorString = [[NSString alloc] initWithFormat:#"Connection failed! Error - %# %# %#", [error localizedDescription], [error description], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]]; NSLog(#"%#",errorString);
[errorString release];
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-GET FULL DATA HERE-=-=-=-=-=-=-=-=--=-=-=-=-=-=-
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *dataString = [[NSString alloc] initWithData:_receivedData encoding:NSUTF8StringEncoding];
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART START-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //
NSString *testXMLString = [NSString stringWithContentsOfURL:myURL usedEncoding:nil error:nil];
// -=-=-=-=-=-=-=-=-=-=Parse the XML into a dictionary-=-=-=-=-=-=-=-=-=-=
NSError *parseError = nil;
_xmlDictionary = [XMLReader dictionaryForXMLString:testXMLString error:&parseError];
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART END-=-=-=-=-=-=-=
_titleArr = [[NSArray alloc] initWithArray:[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"name"] valueForKey:#"text"]];
_IDArr = [[NSArray alloc] [[[_xmlDictionary objectForKey:#"result"] objectForKey:#"id"] valueForKey:#"text"]];
_priceArr= [[NSArray alloc][[[_xmlDictionary objectForKey:#"result"] objectForKey:#"price"] valueForKey:#"text"]];
_ImageURLArr=[[NSArray alloc][[[_xmlDictionary objectForKey:#"result"] objectForKey:#"img"] valueForKey:#"text"]];
[connection release];
[_receivedData release];
[dataString release];
_didDataLoaded=TRUE;
[_myTableView reloadData]; // IBOutlet property
[self.tableView reloadData]; //default
}
//-=-=-=-=-=-=-=-=-=-=-Connection methods END-=-=-=-=-=-=-=-=-=-
- (void)viewDidLoad {
[super viewDidLoad];
_didDataLoaded=FALSE;
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART START-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//-=-==-=-=-=-=-=-=-=-=-=-=--=-=START Shit with connection-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=
NSString* params = #"request_params";
NSURL* url = [NSURL URLWithString:#"my URL"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
request.HTTPMethod = #"POST";
request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
NSLog(#"Connecting...");
_receivedData = [[NSMutableData data] retain];
} else {
NSLog(#"Connecting error");
}
}
//-=-==-=-=--=-==-=-=-=-=-=--=-==---=-=--==-=-=-=-=-TableView methods-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=--=-=-=-=-=-=-=
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (_didDataLoaded == FALSE) {
return 1;
}
else return self.titleArr.count;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { return 1; }
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"creatures"];
UIImage *creatureImage = nil;
if (_didDataLoaded == FALSE) {
cell.textLabel.text=#"Downloading...";
cell.detailTextLabel.text= #"downloading...";
} else {
cell.textLabel.text = [self.titleArr objectAtIndex:indexPath.row];
cell.detailTextLabel.text= _IDArr[indexPath.row];
NSString *img = self.ImageURLArr[indexPath.row];
creatureImage =[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:img]]]; cell.imageView.image = creatureImage;
}
return cell;
}
#end
You can move the relevant code from viewDidLoad to a specific method, something like:
- (void)loadXMLData {
// Initiate your loading/parsing
}
In viewDidLoad just call this method:
- (void)viewDidLoad {
[super viewDidLoad];
[self loadXMLData];
}
This way you can call [self loadXMLData] multiple times.
However... be careful with calling [tableView reloadData] from inside a UITableViewDelegate method implementation, as this will cause the tableview to call (at least some of the) delegate methods, which can cause recursive loops or other odd behaviour.

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"]];

flow of json to tableview

i have another problem this time, i'm fetching json codes that will be used to populate the tableview i have in my xib so, to start with my .h file
#interface FirstViewController : UIViewController<UITableViewDelegate, UITableViewDataSource, ASIHTTPRequestDelegate> {
NSMutableArray *resultArray;
IBOutlet UITableView *thetableView;
NSMutableData *responseData;
}
#property (nonatomic,retain) NSArray *arrayTypes;
#property (nonatomic,retain) NSMutableArray *resultArray;
#property (nonatomic,retain) IBOutlet UITableView *thetableView;
in my .m file i implemented this
- (void) viewDidLoad{
responseData = [[NSMutableData data]retain];
NSURL *url = [NSURL URLWithString:#"http://localhost/fetch.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
[super viewDidLoad];
[self.thetableView reloadData];
}
in the connectiondidfinishloading:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSLog(#"%#", responseString);
NSDictionary *dictionary = [responseString JSONValue];
NSMutableArray *response = [dictionary valueForKey:#"itemn"];
resultArray = [[NSArray alloc] initWithArray:response];
}
and now the problem, the tableview has implemented both the numberofrowsinsection and didselectrowatindextpath methods but the latter is never called as the size of the array is 0 and even reloading, it doesn't work am i missing something or is there a similar tutorial to follow? sorry for the length just hoping the infos will be useful
you should reload tableview once you have the complete data..see the updated code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSLog(#"%#", responseString);
NSDictionary *dictionary = [responseString JSONValue];
NSMutableArray *response = [dictionary valueForKey:#"itemn"];
resultArray = [[NSArray alloc] initWithArray:response];
//Reload your table with data..
[self.thetableView reloadData];
}

Resources