Failure to display data in UITableView - ios

I have a UITableView that has to be populated with the contents stored in an array. I have displayed the array in the NSLog which comes out just fine but it is not visible in the uitableview. The problem is that the program does not enter the cellForRowAtIndexPath method. I am not sure as to which code i should be adding to this question to make it easier to understand so please ask me for the code.
#import "SubList.h"
#import "SubListParser.h"
#import "LoginParser.h"
#implementation SubList
#synthesize theXML1,FolderID,UserID;
NSString *loginUserId;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
self.FolderID=FolderID ;
self.UserID=UserID;
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self initWithData];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)initWithData{
//[self GetChilds:FolderID UserID:loginUserId];
}
-(void)GetUserLoginId:(NSString *)UserIdReceved{
loginUserId=UserIdReceved;
}
-(void)GetChilds:(NSString*)FolderIDRecvd UserID:(NSString*)userID{
NSString *_FolderID=FolderIDRecvd;
NSString *_UserID=loginUserId;
//?? what to do here? aa gye bhai yha pe folder id nad user id? try out now ok
// NSLog(#"hi yaar response toh aa rha ha that mean s values toh ha hmare pass haan storyboard ka koi laucha hai ny yaar do min de dekhta hu",FolderIDRecvd,loginUserId);
NSString *soapMsg=[NSString stringWithFormat:#"<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><TreeDataSubFolder xmlns='http://tempuri.org/'><FolderID>%#</FolderID><UserId>%#</UserId></TreeDataSubFolder></soap:Body></soap:Envelope>",_FolderID,_UserID];
NSLog(#"%#",soapMsg);
NSURL *url=[NSURL URLWithString:#"http://192.168.1.5/interlogicsmobile/interlogics.asmx?op=TreeDataSubFolder"];
xmlparser1 = [[NSXMLParser alloc] initWithContentsOfURL:url];
NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:url];
NSString *msgLength=[NSString stringWithFormat:#"%d",[soapMsg length]];
NSLog(#"Message Length=%#",msgLength);
[req addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue:#"http://tempuri.org/TreeDataSubFolder" forHTTPHeaderField:#"SOAPAction"];
[req addValue:#"length" forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
//[activityIndicator startAnimating];
conn1=[[NSURLConnection alloc]initWithRequest:req delegate:self];
if(conn1){
webdata1=[NSMutableData data] ;
}
}
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
int responseStausCode = [httpResponse statusCode];
NSLog(#"code: %d", responseStausCode);
[webdata1 setLength: 0];
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
[webdata1 appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
NSLog(#"DONE. Received Bytes: %d", [webdata1 length]);
theXML1 = [[NSString alloc]
initWithBytes: [webdata1 mutableBytes]
length:[webdata1 length]
encoding:NSUTF8StringEncoding];
//---shows the XML---
//NSLog(#"%#",theXML1);
SubListParser *parserObjForData1=[[SubListParser alloc]init];
SubFolderData=[[NSMutableArray alloc]init];
SubFolderData=[parserObjForData1 UserXMLParser1:webdata1];
[SublistSet reloadData];
}
- (void)viewDidUnload
{
[SublistSet reloadData];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[SublistSet reloadData];
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (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 [SubFolderData count]/2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"*******************called tablevied did load*********************");
int row = [indexPath row]*2;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
for (int i=0; i<=[SubFolderData count]/2; i++) {
NSString *filename = [SubFolderData objectAtIndex:row];
NSString *ext = [filename pathExtension];
if ([ext isEqualToString:#"doc"] || [ext isEqualToString:#"DOC"]) {
[cell.imageView setImage:[UIImage imageNamed:#"DOC.png"]];
} else if ([ext isEqualToString:#"jpg"]|| [ext isEqualToString:#"JPG"]) {
[cell.imageView setImage:[UIImage imageNamed:#"JPG.png"]];
}else if([ext isEqualToString:#"pdf"]|| [ext isEqualToString:#"PDF"]){
[cell.imageView setImage:[UIImage imageNamed:#"PDF.png"]];
}else if([ext isEqualToString:#""]){
[cell.imageView setImage:[UIImage imageNamed:#"Folder2.png"]];
}else if([ext isEqualToString:#"docx"]|| [ext isEqualToString:#"DOCX"]){
[cell.imageView setImage:[UIImage imageNamed:#"DOCX.png"]];
}else if([ext isEqualToString:#"TIF"]|| [ext isEqualToString:#"tif"]){
[cell.imageView setImage:[UIImage imageNamed:#"TIFF.png"]];
}else if([ext isEqualToString:#"png"]|| [ext isEqualToString:#"PNG"]){
[cell.imageView setImage:[UIImage imageNamed:#"PNG.png"]];
}else if([ext isEqualToString:#"gif"]|| [ext isEqualToString:#"GIF"]){
[cell.imageView setImage:[UIImage imageNamed:#"GIF.png"]];
}else if([ext isEqualToString:#"jpeg"]|| [ext isEqualToString:#"JPEG"]){
[cell.imageView setImage:[UIImage imageNamed:#"JPG.png"]];
}
}
// Configure the cell...
cell.textLabel.text=[SubFolderData objectAtIndex:row];
cell.detailTextLabel.text =[SubFolderData objectAtIndex:row+1];
cell.textLabel.numberOfLines = 0;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
return cell;
}
/*
// Override to support conditional editing of the table view.
#end

Related

Textfields as search bar getting crash

I am using this code for textfiled as search bar.Here is my code. but i am getting crash for range on textfield.if i start entering then its crashing.Even not able to handle case sensitive text also
#import "ViewController.h"
#import "AFNetworking.h"
#import <QuartzCore/QuartzCore.h>
#interface ViewController ()
{
NSMutableArray *countryArray;
NSMutableArray *searchArray;
NSString *searchTextString;
BOOL isFilter;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_countryView.hidden = true;
self->countryArray = [[NSMutableArray alloc] init];
[self makeRestuarantsRequests];
_tableView.layer.borderColor = [UIColor lightGrayColor].CGColor;
_tableView.layer.borderWidth = 1;
_tableView.layer.cornerRadius=5;
[self.searchTextField addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}
-(void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter]removeObserver:self
name:UITextFieldTextDidChangeNotification object:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - AFNetworking
-(void)makeRestuarantsRequests{
NSURL *url = [NSURL URLWithString:#"example url"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject) {
self->countryArray = [responseObject objectForKey:#"data"];
[self.tableView reloadData];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseObject) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
}
#pragma mark - Tableview Delegate and Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(isFilter)
{
return [searchArray count];
}
else
return [countryArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary *tempDictionary= [self->countryArray objectAtIndex:indexPath.row];
if(isFilter)
{
cell.textLabel.text=[searchArray objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text = [tempDictionary objectForKey:#"name"];
}
// cell.textLabel.text = [tempDictionary objectForKey:#"name"];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[_SelectCountryButton setTitle:cell.textLabel.text forState:UIControlStateNormal];
_countryView.hidden = true;
}
-(void)textFieldDidChange:(UITextField *)textField
{
searchTextString=textField.text;
[self updateSearchArray:searchTextString];
}
-(void)updateSearchArray:(NSString *)searchText
{
if(searchText.length==0)
{
isFilter=NO;
}
else{
isFilter=YES;
searchArray=[[NSMutableArray alloc]init];
for(NSString *string in countryArray){
NSRange stringRange=[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location !=NSNotFound){
[searchArray addObject:string];
}
}
[self.tableView reloadData];}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
#pragma mark UITextFieldDelegates
- (IBAction)SelectCountry:(id)sender {
_countryView.hidden = false;
}
#end
Getting crash error :
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI rangeOfString:options:]: unrecognized selector sent to instance 0x10128b4f0
error code :
-(void)updateSearchArray:(NSString *)searchText
{
if(searchText.length==0)
{
isFilter=NO;
}
else{
isFilter=YES;
searchArray=[[NSMutableArray alloc]init];
for(NSString *string in countryArray){
NSRange stringRange=[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location !=NSNotFound){
[searchArray addObject:string];
}
}
[self.tableView reloadData];}
}
Please help me out.How can i solve this issues.
Thanks in advance !
UPDATE :
{"response":true,"message":"country.","data":[{"id":1,"name":"Afghanistan"},{"id":2,"name":"Albania"},{"id":3,"name":"Algeria"},{"id":4,"name":"American Samoa"},{"id":5,"name":"Andorra"},{"id":6,"name":"Angola"}]}
well i have good approach with predicate
well according to you jsonResponse
// so forEach loop should like this
for(NSDictionary *Dic in CountryArray){
NSString*str=[NSString stringWithFormat:#"%#",[dic objectForKey:#"name"]];
}
// well i am not using for each loop instead of that i have nsmutablearray name as _searchArraySingle is same like your countryArray with predicate
// if you are using textfield in place of default Searchbar so use this then use NSPredicate
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(textFieldTextDidChangeOneCI:)
name:UITextFieldTextDidChangeNotification
object:searchTxt];
SearchBar.delegate = (id)self;
}
-(void)textFieldTextDidChangeOneCI:(NSNotification *)notification {
UITextField *textfield=[notification object];
[self predicatChangeText:textfield.text];
// NSLog(#"%#",textfield.text);
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
-(void)predicatChangeText:(NSString*)text{
// myJSON.array
NSPredicate *predicateString = [NSPredicate predicateWithFormat:#"%K contains[cd] %#", #"name", text];
_filteredArray = [NSMutableArray arrayWithArray:[_searchArraySingle filteredArrayUsingPredicate:predicateString]];
NSLog(#"_filteredArray=%lu",(unsigned long)[_filteredArray count]);
[self.tableView reloadData];
}
- (IBAction)cancleSearch:(id)sender {
searchTxt.text=#"";
if (_filteredArray) {
_filteredArray=nil;
}
[self.searchTxt resignFirstResponder];
_filteredArray = myJSON.array;
[self.tableView reloadData];
}
Might this will help you out !!!! GoodLuck

Xcode Table view Data is getting duplicated when I pull to refresh

Hi My data is getting duplicated every time I use the pull to refresh.. for eg. 5 initial entries in the table view are doubled to 10 with one pull to refresh and adding 5 more in the subsequent pull to refresh. How can I stop the duplication.. I would like to make sure that only new items are downloaded and existing data in the table is not downloaded again.
#implementation RootViewController
#synthesize allEntries = _allEntries;
#synthesize feeds = _feeds;
#synthesize queue = _queue;
#synthesize webViewController = _webViewController;
#pragma mark -
#pragma mark View lifecycle
- (void)addRows {
RSSEntry *entry1 = [[[RSSEntry alloc] initWithBlogTitle:#"1"
articleTitle:#"1"
articleUrl:#"1"
articleDate:[NSDate date]] autorelease];
RSSEntry *entry2 = [[[RSSEntry alloc] initWithBlogTitle:#"2"
articleTitle:#"2"
articleUrl:#"2"
articleDate:[NSDate date]] autorelease];
RSSEntry *entry3 = [[[RSSEntry alloc] initWithBlogTitle:#"3"
articleTitle:#"3"
articleUrl:#"3"
articleDate:[NSDate date]] autorelease];
[_allEntries insertObject:entry1 atIndex:0];
[_allEntries insertObject:entry2 atIndex:0];
[_allEntries insertObject:entry3 atIndex:0];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Songs";
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feeds = [NSArray arrayWithObjects:
#"http://hindisongs.bestofindia.co/?feed=rss2",
nil];
self.refreshControl = [UIRefreshControl new];
self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:#"Pull to refresh"];
[self.refreshControl addTarget:self action:#selector(bindDatas) forControlEvents:UIControlEventValueChanged];
[self bindDatas]; //called at the first time
}
-(void)bindDatas
{
//GET YOUR DATAS HERE…
for (NSString *feed in _feeds) {
NSURL *url = [NSURL URLWithString:feed];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[_queue addOperation:request];
}
//update the tableView
[self.tableView reloadData];
if(self.refreshControl != nil && self.refreshControl.isRefreshing == TRUE)
{
[self.refreshControl endRefreshing];
}
}
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"link"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate] autorelease];
[entries addObject:entry];
}
}
}
- (void)parseAtom:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSString *blogTitle = [rootElement valueForChild:#"title"];
NSArray *items = [rootElement elementsForName:#"entry"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = nil;
NSArray *links = [item elementsForName:#"link"];
for(GDataXMLElement *link in links) {
NSString *rel = [[link attributeForName:#"rel"] stringValue];
NSString *type = [[link attributeForName:#"type"] stringValue];
if ([rel compare:#"alternate"] == NSOrderedSame &&
[type compare:#"text/html"] == NSOrderedSame) {
articleUrl = [[link attributeForName:#"href"] stringValue];
}
}
NSString *articleDateString = [item valueForChild:#"updated"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC3339];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate] autorelease];
[entries addObject:entry];
}
}
- (void)parseFeed:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
[self parseRss:rootElement entries:entries];
} else if ([rootElement.name compare:#"feed"] == NSOrderedSame) {
[self parseAtom:rootElement entries:entries];
} else {
NSLog(#"Unsupported root element: %#", rootElement.name);
}
}
- (void)requestFinished:(ASIHTTPRequest *)request {
[_queue addOperationWithBlock:^{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil) {
NSLog(#"Failed to parse %#", request.url);
} else {
NSMutableArray *entries = [NSMutableArray array];
[self parseFeed:doc.rootElement entries:entries];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries) {
int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
RSSEntry *entry1 = (RSSEntry *) a;
RSSEntry *entry2 = (RSSEntry *) b;
return [entry1.articleDate compare:entry2.articleDate];
}];
[_allEntries insertObject:entry atIndex:insertIdx];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
withRowAnimation:UITableViewRowAnimationRight];
}
}];
}
}];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
NSError *error = [request error];
NSLog(#"Error: %#", error);
}
/*
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_allEntries count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
cell.textLabel.text = entry.articleTitle;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%# - %#", articleDateString, entry.blogTitle];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source.
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (_webViewController == nil) {
self.webViewController = [[[WebViewController alloc] initWithNibName:#"WebViewController" bundle:[NSBundle mainBundle]] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
_webViewController.entry = entry;
[self.navigationController pushViewController:_webViewController animated:YES];
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
self.webViewController = nil;
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[_allEntries release];
_allEntries = nil;
[_queue release];
_queue = nil;
[_feeds release];
_feeds = nil;
[_webViewController release];
_webViewController = nil;
[super dealloc];
}
The issue is that you keep inserting object to _allEntries without ever reseting it. You will want to empty it out at some point, either when the user pulls to refresh or when the new data comes in before you add any new objects to it.
[_allEntries removeAllObjects];
Try putting it at the start of bindDatas.

How to set badge value in Tab bar?

i have to read datas from xml and have to display values in view controller. am using tab barcontroller . where i have to read xml data and have to display it in tab bar as badge. here is my controller code.
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"Event"]) {
//Initialize the array.
rssOutputData = [[NSMutableArray alloc] init];
mycount = [attributeDict objectForKey:#"count"];
NSLog(#"Reading count value :%#",mycount);
}
else if([elementName isEqualToString:#"eventdashboard"]) {
//Initialize the book.
aEvent = [[Eventlist alloc] init];
//Extract the attribute here.
aEvent.id = [[attributeDict objectForKey:#"userid"] integerValue];
NSLog(#"Reading id value :%d", aEvent.id);
}
NSLog(#"Processing Element: %#", elementName);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(!nodecontent)
nodecontent = [[NSMutableString alloc] initWithString:string];else
[nodecontent appendString:string];
NSLog(#"Processing Value: %#", nodecontent);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:#"Event"])
return;
if([elementName isEqualToString:#"eventdashboard"]) {
[rssOutputData addObject:aEvent];
[aEvent release];
aEvent= nil;
}
else
[aEvent setValue:nodecontent forKey:elementName];
[nodecontent release];
nodecontent = nil;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bg2.jpeg"]];
NSLog(#"%d",memberid);
myid = [SingleTonClass sinlgeTon].memberIdOne;
NSString *post =[[NSString alloc] initWithFormat:#"userid=%d",myid];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"http://journalonline.in/cfts/dashboards/dashboard?"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
// [theRequest addRequestHeader:#"Content-Type" value:#"application/xml"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/xml" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
}
}
-(void)viewWillAppear:(BOOL)animated{
[tblView reloadData];
}
-(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
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
eventarray = [[NSMutableArray alloc]init];
xmlParserObject = [[NSXMLParser alloc] initWithData:webData];
[xmlParserObject setDelegate:self];
[xmlParserObject parse];
for (int i =0; i<[rssOutputData count]; i++) {
Eventlist *log = [rssOutputData objectAtIndex:i];
eventid = log.id;
NSLog(#"%d",eventid);
Invit = log.invitationdet;
NSLog(#"%#",Invit);
[eventarray addObject:log];
}
[connection release];
[tblView reloadData];
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
NSString * segueIdentifier = [segue identifier];
if([segueIdentifier isEqualToString:#"MainEventList"]){
UINavigationController *nav = [segue destinationViewController];
MaineventListController *MVC = (MaineventListController *)nav.topViewController;
MVC.memberid1 = [SingleTonClass sinlgeTon].memberIdOne;
NSLog(#"%d",MVC.memberid1);
}
if ([segue.identifier isEqualToString:#"EventListDetail"])
{
NSIndexPath *indexPath = [tblView indexPathForSelectedRow];
[[SingleTonClass sinlgeTon] addObjectsColorArray:[NSString stringWithFormat:#"%d",indexPath.row]];
MainEventDetailController *destViewController = segue.destinationViewController;
MainEvent *aEvent1 = [eventarray objectAtIndex:indexPath.row];
destViewController.eveID = aEvent1.id;
destViewController.usrid = [SingleTonClass sinlgeTon].memberIdOne;
}
}
-(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [eventarray count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0)
return [eventarray count];
if (section == 1)
return 1;
return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"eventCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if(indexPath.section == 0)
{
Eventlist *msglist = [eventarray objectAtIndex:indexPath.row];
cell.textLabel.text = msglist.invitationdet;
NSLog(#"Array %#",[SingleTonClass sinlgeTon].colorArray);
NSInteger stat=msglist.readflag;
if([[SingleTonClass sinlgeTon].colorArray containsObject:[NSString stringWithFormat:#"%d",indexPath.row]] || stat == 1 ) {
NSInteger stat1 = msglist.responseflag;
if(stat1 == 1){
cell.textLabel.textColor = [UIColor yellowColor];
}
else {
cell.textLabel.textColor = [UIColor redColor];
}
}
else{
cell.textLabel.textColor = [UIColor greenColor];
}
cell.backgroundColor = [UIColor blackColor];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if(indexPath.section == 1)
{
UIButton *viewmoreButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
viewmoreButton.frame = CGRectMake(200.0f, 5.0f, 80.0f, 30.0f);
[viewmoreButton setTitle:#"View More" forState:UIControlStateNormal];
[cell addSubview:viewmoreButton];
[viewmoreButton addTarget:self
action:#selector(viewMore:)
forControlEvents:UIControlEventTouchUpInside];
cell.backgroundColor = [ UIColor blackColor];
}
return cell;
}
- (void)viewMore:(id)sender
{
[self performSegueWithIdentifier:#"MainEventList" sender:sender];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void) dealloc
{
[xmlParserObject release];
[super dealloc];
}
Here am reading a value from XML
mycount = [attributeDict objectForKey:#"count"];
I dont know to display in tab bar as badge. i tried to display it under ViewdidLoad but didnt worked
pls help me friends
Let me tell you the simplest way to set badge value :
[[self navigationController] tabBarItem].badgeValue = #"YourBadgeValue";
Vineet Singh's answer is good if you want to change the badge for the current tab. If instead you need to change the value for another tab you have in your tab bar, use the following:
Objective-C
[[self.tabBarController.tabBar.items objectAtIndex:0] setBadgeValue:nil];
Swift
tabBarController?.tabBar.items?[0].badgeValue = nil
Remember to replace the index I used with the actual tab you want to edit the value for.
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
UITabBarItem *tbItem = (UITabBarItem *)[appDelegate.tabBarController.tabBar.items objectAtIndex:tabIndex];
tbItem.badgeValue = [NSString stringWithFormat:#"%i", count];
swift 2.0:
self.navigationController!.tabBarItem.badgeValue = "YourBadgeValue"
Try this:
tabBarItem.badgeValue = [NSString stringWithFormat:#"%d",count];
I see some answers about setting this on the TabItem, but if the tab has never been loaded the viewDidLoad function will never get loaded. This is especially important when you are trying to create a background process such as push notification handling set a tab's badge. It's much more likely you will need your TabViewController to handle the badge setting. Tags on the TabItem seem more appropriate and then flip through the tabs until you find the one you want to update.
Cheers!
int indexOfTabbarItem = 0;
NSString *badgeValue = [NSString stringWithFormat:#"%lu", (long)countUnreadMessages];
[[[[self viewControllers] objectAtIndex:indexOfTabbarItem] tabBarItem] setBadgeValue:([badgeValue isEqualToString:#"0"]) ? nil : badgeValue];
This worked for me. Some times you have to find the right controller and then its item to set it. Cheers.
For ionic angular, you just bind the value to tabBadge
<ion-tab [root]="tab3Root" tabIcon="notifications" tabBadgeStyle="red" tabBadge={{totalUnread}}></ion-tab>

Lazytableimages not load on custom cell storyboard

I'm trying to load Lazy Tableview in a custom cell in storyboard, but the table view just looks blank:
This is the source code:
LazyLoadTable.m
#import "CellData.h"
#import "LazyLoadTableView.h"
#import "CustomCell.h"
#import "ParseOperation.h"
#import "ImageDownloader.h"
#define kCustomRowHeight 157
#define kCustomRowCount 1
static NSString *const xmlDataUrl =
#"http://itunes.apple.com/us/rss/topfreeapplications/limit=300/xml";
#interface LazyLoadTableView ()
#end
#implementation LazyLoadTableView
#synthesize tableElements;
#synthesize queue;
#synthesize connection;
#synthesize xmlData;
#synthesize tView;
#synthesize imageDownloadsInProgress;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
self.tableElements=[[NSMutableArray alloc] init];
self.imageDownloadsInProgress = [NSMutableDictionary dictionary];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title=#"Menu";
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:xmlDataUrl]];
self.connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
// Test the validity of the connection object.
NSAssert(self.connection != nil, #"Failure to create URL connection.");
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int count = [tableElements count];
// ff there's no data yet, return enough rows to fill the screen
if (count == 0)
{
return kCustomRowCount;
}
return count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// customize the appearance of table view cells
static NSString *placeholderCellIdentifier = #"PlaceholderCell";
// add a placeholder cell while waiting on table data
int nodeCount = [self.tableElements count];
if (nodeCount == 0 && indexPath.row == 0)
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:placeholderCellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:placeholderCellIdentifier];
cell.detailTextLabel.textAlignment = NSTextAlignmentCenter ;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.detailTextLabel.text = #"Loading…";
return cell;
}
static NSString *CustomCellIdentifier = #"CustomCellIdentifier";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
for (id oneObject in nib) if ([oneObject isKindOfClass:[CustomCell class]])
cell = (CustomCell *) [nib objectAtIndex:0];
}
// Leave cells empty if there's no data yet
if (nodeCount > 0)
{
// Set up the cell...
CellData *cellData = (self.tableElements)[indexPath.row];
cell.name.text = cellData.name;
// Only load cached images; defer new downloads until scrolling ends
if (!cellData.icon)
{
if (self.tView.dragging == NO && self.tView.decelerating == NO)
{
[self startIconDownload:cellData forIndexPath:indexPath];
}
// if a download is deferred or in progress, return a placeholder image
cell.itemImage.image = [UIImage imageNamed:#"Placeholder.png"];
}
else
{
cell.itemImage.image = cellData.icon;
}
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return kCustomRowHeight;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.xmlData = [NSMutableData data]; // start off with new data
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.xmlData appendData:data]; // append incoming data
}
#pragma mark -
#pragma mark NSURLConnection delegate methods
- (void)handleError:(NSError *)error
{
NSString *errorMessage = [error localizedDescription];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Cannot Show Data"
message:errorMessage
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if ([error code] == kCFURLErrorNotConnectedToInternet)
{
// if we can identify the error, we can present a more precise message to the user.
NSDictionary *userInfo = #{NSLocalizedDescriptionKey: #"No Connection Error"};
NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain
code:kCFURLErrorNotConnectedToInternet
userInfo:userInfo];
[self handleError:noConnectionError];
}
else
{
// otherwise handle the error generically
[self handleError:error];
}
self.connection = nil; // release our connection
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.connection = nil; // release our connection
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// create the queue to run our ParseOperation
self.queue = [[NSOperationQueue alloc] init];
ParseOperation *operation = [[ParseOperation alloc] initWithData:self.xmlData delegate:self];
[queue addOperation:operation]; // this will start the "ParseOperation"
self.xmlData = nil;
}
- (void)didFinishParsing:(NSArray *)cellDataList
{
[self performSelectorOnMainThread:#selector(handleLoadedApps:) withObject:cellDataList waitUntilDone:NO];
self.queue = nil; // we are finished with the queue and our ParseOperation
}
- (void)parseErrorOccurred:(NSError *)error
{
[self performSelectorOnMainThread:#selector(handleError:) withObject:error waitUntilDone:NO];
}
- (void)handleLoadedApps:(NSArray *)loadedCellData
{
[self.tableElements addObjectsFromArray:loadedCellData];
// tell our table view to reload its data, now that parsing has completed
[self.tView reloadData];
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)startIconDownload:(CellData *)cellData forIndexPath:(NSIndexPath *)indexPath
{
ImageDownloader *imageDownloader = imageDownloadsInProgress[indexPath];
if (imageDownloader == nil)
{
imageDownloader = [[ImageDownloader alloc] init];
imageDownloader.cellData = cellData;
imageDownloader.indexPathInTableView = indexPath;
imageDownloader.delegate = self;
imageDownloadsInProgress[indexPath] = imageDownloader;
[imageDownloader startDownload];
}
}
// this method is used in case the user scrolled into a set of cells that don't have their app icons yet
- (void)loadImagesForOnscreenRows
{
if ([self.tableElements count] > 0)
{
NSArray *visiblePaths = [self.tView indexPathsForVisibleRows];
for (NSIndexPath *indexPath in visiblePaths)
{
CellData *cellData = (self.tableElements)[indexPath.row];
if (!cellData.icon) // avoid the app icon download if the app already has an icon
{
[self startIconDownload:cellData forIndexPath:indexPath];
}
}
}
}
// called by our ImageDownloader when an icon is ready to be displayed
- (void)imageDidLoad:(NSIndexPath *)indexPath
{
ImageDownloader *imageDownloader = imageDownloadsInProgress[indexPath];
if (imageDownloader != nil)
{
CustomCell *cell = (CustomCell *)[self.tView cellForRowAtIndexPath:imageDownloader.indexPathInTableView];
// Display the newly loaded image
cell.itemImage.image = imageDownloader.cellData.icon;
}
}
#pragma mark -
#pragma mark Deferred image loading (UIScrollViewDelegate)
// Load images for all onscreen rows when scrolling is finished
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
if (!decelerate)
{
[self loadImagesForOnscreenRows];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self loadImagesForOnscreenRows];
}
#end
CustomCell.m
#import "CustomCell.h"
#implementation CustomCell
#synthesize itemImage;
#synthesize name;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
Didn't read through all that code but it looks like you are trying to lazy load an image with some text. I highly recommend using SDWebImage for the lazy loading. It's simple and very straightforward to set up.

My program does not work in NSURLConnection before tableView

Why doesn't my program work in NSURLConnection before tableView?
// MyLoxFileTVContoller.m
#import "MyLoxFileTVContoller.h"
#import "xml_myloxfile.h"
#import "DetailViewController.h"
#implementation MyLoxFileTVContoller
#synthesize myloxfileArray;
#synthesize exportId_data_Array,readFG_data_Array,receiverId_data_Array,referenceId_data_Array,referenceName_data_Array,reportFullPath_data_Array,reportName_data_Array,senderId_data_Array,senderName_data_Array,sentDate_data_Array,subject_data_Array;
#synthesize detailViewController;
#synthesize window = _window;
#synthesize navigationController;
#synthesize delegate;
#synthesize unReadCount;
#synthesize webData;
-(void)doParse{
NSLog(#"doParse"); //debug
[myloxfileArray removeAllObjects];
NSString *soapMessage = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:con=\"http://controller.exportingreportwebservice.lox.org/\">\n"
"<soapenv:Header/>\n"
"<soapenv:Body>\n"
"<con:getReport>\n"
"<arg0>%#</arg0>\n"
"</con:getReport>\n"
"</soapenv:Body>\n"
//"</soapenv:Envelope>\n", nameInput.text
"</soapenv:Envelope>\n", #"2711"
];
//NSLog(soapMessage);
NSURL *url = [NSURL URLWithString:#"http://iloxley.loxley.co.th:8081/ExportingReportWebservice/ExportingReportWebservice?wsdl"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
NSLog(#"if theConnection"); //debug
webData = [NSMutableData data];
}
else
{
NSLog(#"theConnection is NULL");
}
NSLog(#"end doParse"); //debug
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"connection didReceiveResponse"); //debug
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"connection didReceiveData"); //debug
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"connectionDidFinishLoading"); //debug
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
//NSLog(#"theXML = %# ", theXML);
//NSLog(#"webData = %# ", webData);
//NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithContentsOfURL:theXML];
NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithData: webData];
// create and init our delegate
xml_myloxfile_Parser *parser = [[xml_myloxfile_Parser alloc] initXMLParser];
//set delegate
[nsXmlParser setDelegate:parser];
//parsing...
BOOL success = [nsXmlParser parse];
if (success) {
NSLog(#"if success"); //debug
exportId_data_Array = [parser getExportId_data_Array];
readFG_data_Array = [parser getReadFG_data_Array];
receiverId_data_Array = [parser getReceiverId_data_Array];
referenceId_data_Array = [parser getReferenceId_data_Array];
referenceName_data_Array = [parser getReferenceName_data_Array];
reportFullPath_data_Array = [parser getReportFullPath_data_Array];
reportName_data_Array = [parser getReportName_data_Array];
senderId_data_Array = [parser getSenderId_data_Array];
senderName_data_Array = [parser getSenderName_data_Array];
sentDate_data_Array = [parser getSentDate_data_Array];
subject_data_Array = [parser getSubject_data_Array];
items_exportId = exportId_data_Array;
items_readFG = readFG_data_Array;
items_receiverId = receiverId_data_Array;
items_referenceId = referenceId_data_Array;
items_referenceName = referenceName_data_Array;
items_reportFullPath = reportFullPath_data_Array;
items_reportName = reportName_data_Array;
items_senderId = senderId_data_Array;
items_senderName = senderName_data_Array;
items_sentDate = sentDate_data_Array;
items_subject = subject_data_Array;
NSLog(#"items_subject = %# ", items_subject);
} else {
NSLog(#"fail");
}
}
-(void) loadView
{
NSLog(#"loadView"); //debug
if (items_subject == nil) {
//items_subject = [NSMutableArray arrayWithObjects:#"1",#"2",#"3",nil];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSLog(#"numberOfSectionsInTableView"); //debug
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"tableView numberOfRowsInSection"); //debug
// Return the number of rows in the section.
NSLog(#"[items_subject count] = %d ", [items_subject count]);
return [items_subject count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"tableView cellForRowAtIndexPath"); //debug
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
//cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.textLabel.text = [NSString stringWithFormat:#"%#" ,[items_subject objectAtIndex:indexPath.row]];
// Populate the cell's detail text label.
NSString *detailText = [NSString stringWithFormat:#"date: %# from: %# reference: %#",
[[items_sentDate objectAtIndex:indexPath.row] lowercaseString],[[items_senderName objectAtIndex:indexPath.row] lowercaseString],[[items_referenceName objectAtIndex:indexPath.row] lowercaseString]];
[[cell detailTextLabel] setText:detailText];
//CGAffineTransform translate = CGAffineTransformMakeTranslation(10.0, 0.0);
//[[cell detailTextLabel] setTransform:translate];
//unReadCount = 0;
if([[items_readFG objectAtIndex:indexPath.row] isEqualToString:#"N"]){
cell.textLabel.textColor = [UIColor redColor];
unReadCount = unReadCount+1;
}else{
cell.textLabel.textColor = [UIColor blackColor];
unReadCount = unReadCount;
}
NSLog(#"unReadCount = %d ",unReadCount);
//Adding A Badge Number
//[[UIApplication sharedApplication] setApplicationIconBadgeNumber:unReadCount];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"tableView didSelectRowAtIndexPath"); //debug
//sof2
DetailViewController *detailController = [[DetailViewController alloc] initWithNibName:#"DetailView" bundle:nil];
[detailController changeExportIdText:[exportId_data_Array objectAtIndex:indexPath.row]];
[detailController changeReadFGText:[readFG_data_Array objectAtIndex:indexPath.row]];
[detailController changeReceiverIdText:[receiverId_data_Array objectAtIndex:indexPath.row]];
[detailController changeReferenceIdText:[referenceId_data_Array objectAtIndex:indexPath.row]];
[detailController changeReferenceNameText:[referenceName_data_Array objectAtIndex:indexPath.row]];
[detailController changeReportFullPathText:[reportFullPath_data_Array objectAtIndex:indexPath.row]];
[detailController changeReportNameText:[reportName_data_Array objectAtIndex:indexPath.row]];
[detailController changeSenderIdText:[senderId_data_Array objectAtIndex:indexPath.row]];
[detailController changeSenderNameText:[senderName_data_Array objectAtIndex:indexPath.row]];
[detailController changeSentDateText:[sentDate_data_Array objectAtIndex:indexPath.row]];
[detailController changeSubjectText:[subject_data_Array objectAtIndex:indexPath.row]];
//[tableView deselectRowAtIndexPath:indexPath animated:YES];
if([delegate respondsToSelector:#selector(showItemDetails:)])
{
//[delegate showItemDetails:[subject_data_Array objectAtIndex:indexPath.row]];
[delegate showItemDetails:[NSString stringWithFormat:#"%#||%#||%#||%#||%#||%#||%#||%#||%#||%#||%#"
,[exportId_data_Array objectAtIndex:indexPath.row]
,[readFG_data_Array objectAtIndex:indexPath.row]
,[receiverId_data_Array objectAtIndex:indexPath.row]
,[referenceId_data_Array objectAtIndex:indexPath.row]
,[referenceName_data_Array objectAtIndex:indexPath.row]
,[reportFullPath_data_Array objectAtIndex:indexPath.row]
,[reportName_data_Array objectAtIndex:indexPath.row]
,[senderId_data_Array objectAtIndex:indexPath.row]
,[senderName_data_Array objectAtIndex:indexPath.row]
,[sentDate_data_Array objectAtIndex:indexPath.row]
,[subject_data_Array objectAtIndex:indexPath.row]
]];//test multi var'
}
// Alert will pop up when using Simulator or iPod Touch for example
/*
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[note_subject_data_Array objectAtIndex:indexPath.row] message:#"Test" delegate:nil cancelButtonTitle:#"Close" otherButtonTitles:nil];
[alert show];
*/
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
NSLog(#"viewDidLoad"); //debug
[self doParse];
[super viewDidLoad];
}
- (void)viewDidUnload
{
NSLog(#"viewDidUnload"); //debug
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#end
The log:
2012-09-11 15:27:15.377 MyLoxFile[2698:f803] loadView
2012-09-11 15:27:15.378 MyLoxFile[2698:f803] viewDidLoad
2012-09-11 15:27:15.379 MyLoxFile[2698:f803] doParse
2012-09-11 15:27:15.382 MyLoxFile[2698:f803] if theConnection
2012-09-11 15:27:15.382 MyLoxFile[2698:f803] end doParse
2012-09-11 15:27:15.385 MyLoxFile[2698:f803] numberOfSectionsInTableView
2012-09-11 15:27:15.386 MyLoxFile[2698:f803] tableView numberOfRowsInSection
2012-09-11 15:27:15.391 MyLoxFile[2698:f803] [items_subject count] = 0
2012-09-11 15:27:15.454 MyLoxFile[2698:f803] connection didReceiveResponse
2012-09-11 15:27:15.455 MyLoxFile[2698:f803] connection didReceiveData
2012-09-11 15:27:15.455 MyLoxFile[2698:f803] connectionDidFinishLoading
2012-09-11 15:27:15.455 MyLoxFile[2698:f803] DONE. Received Bytes: 1948
2012-09-11 15:27:15.457 MyLoxFile[2698:f803] if success
2012-09-11 15:27:15.457 MyLoxFile[2698:f803] items_subject = (
"Surgical Report ",
"Genotype Report",
"HPV Report"
)
It has data in array but not have in tableView numberOfRowsInSection
Before this code i use XML (not WSDL) it's work
This is My Code -> http://www.vasuta.com/ios/MyLoxFile.zip
It seems like your tableview is load et call its delegates methods before your NSURLConnection finished downloading.
You have launch NSURLConnection by
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
so the connection is asynchronous. You can't be sure whether it finishes before or after your tableview loads its view.
But your can always do a check in your tableview methods to make your app work. For example:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int nbCount = [items_subject count];
if (nbCount == 0)
return 1;
else
return [items_subject count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
int nbCount = [items_subject count];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
if (nbCount ==0)
cell.textLabel.text == #"Loading";
else
{
// your configuration
cell.textLabel.text = [NSString stringWithFormat:#"%#" ,[items_subject objectAtIndex:indexPath.row]];
}
return cell;
}
In your method "ConnectionDidFinishLoading", then your can call [tableview reloaddata] to update your tableview.
[EDIT] on 12/09/2012
I've got your code work(not a nice solution), you should rethink how you organize your viewControllers.
add the IBOutlet TableView to myloxfileController.tableView.
add this line myloxfileContoller.tableView = myloxfileTable; after the line myloxfileContoller.view = myloxfileContoller.tableView; in - (void)viewDidLoad of the interface ViewController .
reload tableview data when connection finished.
add this line [self.tableView reloadData]; after the line items_subject = subject_data_Array; in -(void)connectionDidFinishLoading:(NSURLConnection *)connection of the interface MyLoxFileTVController .
This will work because when the download finished, you reloadData of the IBOutlet TableView.
Have you used [uitableview reloadData] after updating your NSArray?
replace with
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"tableView numberOfRowsInSection"); //debug
// Return the number of rows in the section.
NSLog(#"[items_subject count] = %# ", [items_subject count]);
return [items_subject count];
}

Resources