Search Bar doesn't work on Device in ios - iphone

I created iOS(5.0) application in that I have search Bar, which is used to search the content in server side, while passing keyword entered into search bar the list of content parsed from the xml and shown in Table View,
its working fine in Emulator,.but in device (ipad2 & iphone4s) its not showing table of content were searched.
pls let me know what am making wrong..
Thanks in advance,.
murali.
This is mySearchClass.h
#interface SearchClass : UIViewController<UITableViewDelegate,UITableViewDataSource,UIPickerViewDelegate,UIPickerViewDataSource,UIActionSheetDelegate,UISearchBarDelegate, UISearchDisplayDelegate>
{
AppDelegate *abc;
MBProgressHUD *HUD;
IBOutlet UIScrollView *scrv;
IBOutlet UITableView *tableV;
UISearchBar *searchBar;
IBOutlet UILabel *lblTitle;
IBOutlet UIActionSheet *actionSheet;
IBOutlet UIPickerView *pickerView;
IBOutlet UIButton *btnActionSheet;
UIToolbar *pickerToolBar;
NSMutableArray *arrCate;
NSString *key;
}
-(void)cleartable;
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar;
#end
//======================
This is my SearchClass.m
#implementation SearchClass
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.tabBarItem.image = [UIImage imageNamed:#"search"];
UIImageView *navImg=[[UIImageView alloc]initWithImage:[UIImage imageNamed:#"i-street"]];
self.navigationItem.titleView = navImg;
}
return self;
}
- (void)didReceiveMemoryWarning{ [super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bg1.png"]];
abc = (AppDelegate*)[[UIApplication sharedApplication]delegate];
//self.navigationController.navigationBar.tintColor = [UIColor blackColor];
//[SearchClass initWithNibName:#"" bundle:nil];
//[SearchClass initWithNibName:#"SearchClass" bundle:nil];
arrCate = [[NSMutableArray alloc]initWithObjects:#"Arts & Entertainment",#"Restaurants",#"Bars, Pubs & Clubs",#"Film and Cinema",#"Live Gigs",#"Shops", nil];
pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 43 , 320, 480)];
pickerView.delegate = self;
pickerView.dataSource = self;
[pickerView setShowsSelectionIndicator:YES];
pickerToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 56)];
pickerToolBar.barStyle = UIBarStyleBlackOpaque;
[pickerToolBar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];
UIButton *btnDone = [UIButton buttonWithType:UIButtonTypeCustom];
[btnDone setFrame:CGRectMake(0, 0, 60, 30)];
[btnDone addTarget:self action:#selector(closeActionSheet) forControlEvents:UIControlEventTouchUpInside];
[btnDone setBackgroundImage:[UIImage imageNamed:#"done.png"] forState:UIControlStateNormal];
UIBarButtonItem *dbtn = [[UIBarButtonItem alloc]initWithCustomView:btnDone];
[barItems addObject:dbtn];
[pickerToolBar setItems:barItems animated:YES];
}
-(IBAction)closeActionSheet
{
lblTitle.text=[arrCate objectAtIndex:[pickerView selectedRowInComponent:0]];
[actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [arrCate objectAtIndex:row];
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component
{
return [arrCate count];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component
{
lblTitle.text = [arrCate objectAtIndex:row];
[abc.arrSearch removeAllObjects];
[tableV reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// NSLog(#"table view count seasrch :%d",[abc.arrSearch count]);
return [abc.arrSearch count];
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
NSString *imgUrl;
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
else
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if(indexPath.row > 0)
{
UIImageView *separator = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"line1.png"]];
[cell.contentView addSubview: separator];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImageView *imgbest=[[UIImageView alloc]initWithFrame:CGRectMake(213,4,107,64)];
UIActivityIndicatorView *actSpiner = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
actSpiner.center = imgbest.center;
[actSpiner startAnimating];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(5, 2, 200, 20)];
lbl.textAlignment = UITextAlignmentLeft;
lbl.font = [UIFont fontWithName:#"Helvetica" size:18.0];
lbl.textColor = [UIColor whiteColor];
lbl.backgroundColor = [UIColor clearColor];
lbl.numberOfLines=0;
UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(5, 23, 200, 20)];
lbl1.textAlignment = UITextAlignmentLeft;
lbl1.font = [UIFont fontWithName:#"American Typewriter" size:13.0];
lbl1.textColor = [UIColor whiteColor];
lbl1.backgroundColor = [UIColor clearColor];
lbl1.numberOfLines=0;
UILabel *lbl2 = [[UILabel alloc] initWithFrame:CGRectMake(5,44, 200, 20)];
lbl2.textAlignment = UITextAlignmentLeft;
lbl2.font = [UIFont fontWithName:#"Helvetica-Oblique" size:12.0];
lbl2.textColor = [UIColor whiteColor];
lbl2.backgroundColor = [UIColor clearColor];
lbl2.numberOfLines=0;
if([lblTitle.text isEqualToString:#"Arts & Entertainment"])
{
ArtsClass *arts=[[ArtsClass alloc]init];
arts = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = arts.artThumpImg;
lbl.text=arts.artTitle;
lbl1.text=arts.artDesc;
lbl2.text=arts.artDate;
}
else if([lblTitle.text isEqualToString:#"Restaurants"])
{
ResClass *res=[[ResClass alloc]init];
res = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = res.resLogoImg;
lbl.text=res.resName;
lbl1.text=res.resType;
lbl2.text=res.resPopularDish;
}
else if([lblTitle.text isEqualToString:#"Bars, Pubs & Clubs"])
{
BarClass *bar=[[BarClass alloc]init];
bar = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = bar.barImg;
lbl.text=bar.barTitle;
lbl1.text=bar.barDesc;
lbl2.text=bar.barFacilities;
}
else if([lblTitle.text isEqualToString:#"Film and Cinema"])
{
FilmClass *film=[[FilmClass alloc]init];
film = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = film.filmImg;
lbl.text=film.filmName;
lbl1.text=film.filmSynopsis;
lbl2.text=film.filmReleDate;
}
else if([lblTitle.text isEqualToString:#"Live Gigs"])
{
GigsClass *gigs=[[GigsClass alloc]init];
gigs = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = gigs.eventThumpImg;
lbl.text=gigs.eventTitle;
lbl1.text=gigs.eventCate;
lbl2.text=[NSString stringWithFormat:#"%# - %#",gigs.eventStartDate,gigs.eventEndDate];
}
else if([lblTitle.text isEqualToString:#"Shops"])
{
ShopsClass *shops=[[ShopsClass alloc]init];
shops = [abc.arrSearch objectAtIndex:indexPath.row];
imgUrl = shops.shopThumpImg;
lbl.text=shops.shopName;
lbl1.text=shops.shopDesc;
lbl2.text=shops.shopFacilities;
}
NSURL *url = [NSURL URLWithString:imgUrl] ;
// NSLog(#"image link:%#",url);
dispatch_queue_t currQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
dispatch_async(currQueue,^{
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
imgbest.image = [UIImage imageWithData:data];
});
});
[cell addSubview:actSpiner];
[cell addSubview:imgbest];
[cell addSubview:lbl];
[cell addSubview:lbl1];
[cell addSubview:lbl2];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if([lblTitle.text isEqualToString:#"Arts & Entertainment"])
{
abc.subClassTag=#"ARTS";
abc.classTag = #"GALLERYCLASS";
abc.strTitle = #"Arts & Entertainment";
abc.objArt = [abc.arrArts objectAtIndex:indexPath.row];
}
else if([lblTitle.text isEqualToString:#"Restaurants"])
{
abc.subClassTag=#"RES";
abc.classTag = #"GALLERYCLASS";
abc.strTitle = #"Restaurants";
abc.objRest = [abc.arrRes objectAtIndex:indexPath.row];
}
else if([lblTitle.text isEqualToString:#"Bars, Pubs & Clubs"])
{
abc.subClassTag=#"BAR";
abc.classTag = #"GALLERYCLASS";
abc.strTitle = #"Bars, Pubs & Clubs";
abc.objBar = [abc.arrBars objectAtIndex:indexPath.row];
}
else if([lblTitle.text isEqualToString:#"Film and Cinema"])
{
abc.subClassTag=#"FILMS";
abc.classTag = #"PLAYERCLASS";
abc.strTitle = #"Film and Cinema";
abc.objFilm = [abc.arrFilm objectAtIndex:indexPath.row];
}
else if([lblTitle.text isEqualToString:#"Live Gigs"])
{
abc.subClassTag=#"GIGS";
abc.classTag = #"GALLERYCLASS";
abc.strTitle = #"Live Gigs";
abc.objGig = [abc.arrGigs objectAtIndex:indexPath.row];
}
else if([lblTitle.text isEqualToString:#"Shops"])
{
abc.subClassTag=#"SHOPS";
abc.classTag = #"GALLERYCLASS";
abc.strTitle = #"Shops";
abc.objShop = [abc.arrShops objectAtIndex:indexPath.row];
}
if([abc.classTag isEqualToString:#"PLAYERCLASS"])
{
PlayerClass *pl = [[PlayerClass alloc]init];
[self.navigationController pushViewController:pl animated:YES];
}
else if([abc.classTag isEqualToString:#"GALLERYCLASS"])
{
GalaryClass *gc = [[GalaryClass alloc]init];
[self.navigationController pushViewController:gc animated:YES];
}
}
- (void)viewDidUnload
{
scrv = nil;
tableV = nil;
searchBar = nil;
lblTitle = nil;
[super viewDidUnload];
}
-(IBAction)getCategory:(id)sender
{
[searchBar resignFirstResponder];
actionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:self
cancelButtonTitle:nil //#"Done"
destructiveButtonTitle:nil
otherButtonTitles:nil];
[actionSheet setTag:0];
[actionSheet addSubview:pickerView];
[actionSheet showInView:self.view.superview];
[actionSheet addSubview:pickerToolBar];
[actionSheet showInView:self.view.superview];
[actionSheet setBounds:CGRectMake(0, 0, 320, 430)];
}
-(void)cleartable
{
NSArray * ar=[tableV subviews];
for(int j=0;j<ar.count;j++)
{
NSArray *arr=[[ar objectAtIndex:j]subviews];
for(int i=0;i<arr.count;i++)
{
if([[arr objectAtIndex:i]isKindOfClass:[UILabel class]])
{
[[arr objectAtIndex:i]removeFromSuperview];
}
}
}
}
-(void)showProgress
{
//[searchBar resignFirstResponder];
HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:HUD];
// Set the hud to display with a color
HUD.color = [UIColor colorWithPatternImage:[UIImage imageNamed:#"box4"]];//[UIColor colorWithRed:0.23 green:0.50 blue:0.82 alpha:0.90];
// HUD.opacity =
HUD.delegate = self;
[HUD showWhileExecuting:#selector(download) onTarget:self withObject:nil animated:YES];
}
-(void)download
{
if([NetworkManager checkForNetworkStatus])
{
ParserClass *p =[[ParserClass alloc]init];
NSLog(#"search bar text %# --- %#",key,lblTitle.text);
if (lblTitle.text==#"Arts & Entertainment")
{
[p search:1 string:key];
}else if(lblTitle.text==#"Restaurants")
{
[p search:5 string:key];
}else if(lblTitle.text==#"Bars, Pubs & Clubs")
{
[p search:4 string:key];
}else if(lblTitle.text==#"Film and Cinema")
{
[p search:2 string:key];
}else if(lblTitle.text==#"Live Gigs")
{
[p search:3 string:key];
}else if(lblTitle.text==#"Shops")
{
[p search:6 string:key];
}
[tableV reloadData];
}
else
{
UIAlertView *alrt = [[UIAlertView alloc]initWithTitle:#"Network Error!" message:#"Please Check your Network connetion.." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alrt show];
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 70;
}
- (void)searchBar:(UISearchBar *)searchBar1 textDidChange:(NSString *)searchText
{
if(![lblTitle.text isEqualToString:#"Select Category"])
{
if(searchBar.text.length > 0)
{
key = searchText;
[self showProgress];
// ParserClass *p =[[ParserClass alloc]init];
// NSLog(#"search bar text %# --- %#",searchText,lblTitle.text);
// if (lblTitle.text==#"Arts & Entertainment")
// {
// [p search:1 string:searchText];
// }else if(lblTitle.text==#"Restaurants")
// {
// [p search:5 string:searchText];
// }else if(lblTitle.text==#"Bars, Pubs & Clubs")
// {
// [p search:4 string:searchText];
// }else if(lblTitle.text==#"Film and Cinema")
// {
// [p search:2 string:searchText];
// }else if(lblTitle.text==#"Live Gigs")
// {
// [p search:3 string:searchText];
// }else if(lblTitle.text==#"Shops")
// {
// [p search:6 string:searchText];
// }
//
// [tableV reloadData];
}
else
{
UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:nil message:#"Please Give me some Key words..!" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert1 show];
}
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:#"Please Select any Category..!" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar1
{
[searchBar resignFirstResponder];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar1
{
[searchBar resignFirstResponder];
}
#end
Thanks for ur Reply,.
Murali.

wrong string comparison
if (lblTitle.text==#"Arts & Entertainment")
it should be like this - try this it must work & let me know.
if (lblTitle.text isEqualToString:#"Arts & Entertainment")
I am also having some issues in my search class, i am using JSON url.

Where is the Parsing URL, what are the fields in the xml.
Check your parsing url in ur local browser by manual append method using query string ,working or not.
check by trace path, use console log for print the URL.
Check if u are using localhost url in ur program somewhere else.
Check your delegate for search class.
use this link for your reference.
https://iphonedevsdk.com/forum/iphone-sdk-development/50468-xml-table-view-searchbar.html

Related

indexing not working in tableview

i am trying to achieve indexing on table for that i use following method indexing appears on right side but it is not working code is below
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
NSArray *toBeReturned = [NSArray arrayWithArray:
[#"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|#"
componentsSeparatedByString:#"|"]];
return toBeReturned;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
int foundIndex = 0;
for (int i = 0; i< [mainArray count]; i++) {
// Here you return the name i.e. Honda,Mazda
// and match the title for first letter of name
// and move to that row corresponding to that indexpath as below
NSString *letterString = [[[mainArray valueForKey:#"name"] objectAtIndex:i] substringToIndex:1];
NSLog(#"letterString%#",letterString);
NSLog(#"title%#",title);
if ([[letterString uppercaseString ] compare:title] == NSOrderedDescending){
break;
foundIndex++; }
if(foundIndex > mainArray.count)
foundIndex = mainArray.count;
[table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:foundIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
return 1;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 120;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//—set the text to display for the cell—
NSLog(#"%d",mainArray.count);
NSLog(#"%#",mainArray);
UIImageView *selectionView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 768, 120)];
UIImage *image = [UIImage imageNamed:#"default.png"];
UIImageView* blockView = [[UIImageView alloc] initWithImage:image];
blockView.layer.cornerRadius = 4;
blockView.layer.masksToBounds = YES;
blockView.layer.borderWidth = 2;
blockView.layer.borderColor = [UIColor blackColor].CGColor;
blockView.frame = CGRectMake(5, 5, 110, 110);
// title isKindOfClass:[NSNull class]])
//NSLog(#"%#",[[mainArray valueForKey:#"image"] objectAtIndex:[indexPath row]]);
id obj = [[mainArray valueForKey:#"image"] objectAtIndex:[indexPath row]];
if ([obj isKindOfClass:[NSString class]])
{
[selectionView addSubview:blockView];
}
else {
UIImage *contactImage = [[UIImage alloc]init];
contactImage = [[mainArray valueForKey:#"image"] objectAtIndex:[indexPath row]];
// NSLog(#" array%#",[[mainArray valueForKey:#"image"] objectAtIndex:[indexPath row]]);
NSLog(#" image%#",contactImage);
UIImageView *blockView = [[UIImageView alloc] initWithImage:contactImage];
blockView.frame = CGRectMake(5, 5, 110, 110);
blockView.layer.cornerRadius = 4;
blockView.layer.masksToBounds = YES;
blockView.layer.borderWidth = 2;
blockView.layer.borderColor = [UIColor blackColor].CGColor;
[selectionView addSubview:blockView];
}
NSLog(#" name :%#",[[mainArray valueForKey:#"name"] objectAtIndex:[indexPath row]]);
if ([[[mainArray valueForKey:#"name"] objectAtIndex:[indexPath row]] isEqualToString:#"(null)"]) {
UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(130, 10, 310, 55)];
name.text =#"Name Not Available";
[name setBackgroundColor:[UIColor clearColor]];
[ name setFont:[UIFont fontWithName:#"Arial-BoldMT" size:30]];
name.textColor = [UIColor whiteColor];
[selectionView addSubview:name];
}
else{
UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(130, 10, 310, 55)];
name.text =[[mainArray valueForKey:#"name"] objectAtIndex:[indexPath row]];
[name setBackgroundColor:[UIColor clearColor]];
[ name setFont:[UIFont fontWithName:#"Arial-BoldMT" size:30]];
name.textColor = [UIColor whiteColor];
[selectionView addSubview:name];
}
if ([[[mainArray valueForKey:#"phone"] objectAtIndex:[indexPath row]] isEqualToString:#"Add Number"]) {
UILabel *phone = [[UILabel alloc]initWithFrame:CGRectMake(130, 70, 300, 50)];
phone.text =#"Not Available";
[phone setBackgroundColor:[UIColor clearColor]];
[ phone setFont:[UIFont fontWithName:#"Arial-BoldMT" size:25]];
phone.textColor = [UIColor whiteColor];
[selectionView addSubview:phone];
}
else{
UILabel *phone = [[UILabel alloc]initWithFrame:CGRectMake(130, 70, 300, 50)];
phone.text =[[mainArray valueForKey:#"phone"] objectAtIndex:[indexPath row]];
[phone setBackgroundColor:[UIColor clearColor]];
[ phone setFont:[UIFont fontWithName:#"Arial-BoldMT" size:25]];
phone.textColor = [UIColor whiteColor];
[selectionView addSubview:phone];
}
if ([[[mainArray valueForKey:#"email"] objectAtIndex:[indexPath row]] isEqualToString:#"Add Email"]) {
UILabel *email = [[UILabel alloc]initWithFrame:CGRectMake(420, 40, 350, 50)];
email.text =#"Email Id Not Available";
[email setBackgroundColor:[UIColor clearColor]];
[ email setFont:[UIFont fontWithName:#"Arial-BoldMT" size:20]];
email.textColor = [UIColor whiteColor];
[selectionView addSubview:email];
}
else{
UILabel *email = [[UILabel alloc]initWithFrame:CGRectMake(420, 40, 350, 50)];
email.text =[[mainArray valueForKey:#"email"] objectAtIndex:[indexPath row]];
[email setBackgroundColor:[UIColor clearColor]];
[ email setFont:[UIFont fontWithName:#"Arial-BoldMT" size:20]];
email.textColor = [UIColor whiteColor];
[selectionView addSubview:email];
}
[[cell contentView] addSubview:selectionView];
return cell;
}
what problem i face is it reach top of the table when i click any index and not right index
To use the index your table should really be broken into sections. It looks like currently you are asking the framework to scroll to a specified row and then to scroll to the top of section 0 immediately afterwards.
It may work if you use performSelector to request the scroll after a short delay (it may look nasty). Or possibly if you return -1 from the method (documentation does not support this guess).
The answer really is to use sections in your table and let the framework work as designed.
when we have section 0 then we can do like this
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
NSArray *toBeReturned = [NSArray arrayWithArray:
[#"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z"
componentsSeparatedByString:#"|"]];
return toBeReturned;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
int foundIndex = 0;
for (int i = 0; i< [mainArray count]; i++) {
NSString *letterString = [[[mainArray valueForKey:#"name"] objectAtIndex:i] substringToIndex:1];
NSLog(#"letterString%#",letterString);
NSLog(#"title%#",title);
if ([letterString caseInsensitiveCompare:title] == NSOrderedSame)
{
break;
}
else{
foundIndex++;
NSLog(#"founded index %d",foundIndex);
}
}
NSLog(#"founded index %d",mainArray.count);
NSLog(#"founded index %d",foundIndex);
if(foundIndex >= mainArray.count){
foundIndex = mainArray.count-1;
}
NSLog(#"founded index %d",foundIndex);
[table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:foundIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
return 1;
}
.h
#import <TapkuLibrary/TapkuLibrary.h>
#import <UIKit/UIKit.h>
#import <EventKit/EventKit.h>
#interface CalendarMonthViewController : TKCalendarMonthTableViewController{
NSMutableArray *events;
EKEventStore *eventStore;
NSDate *startDatee;
NSDate *lastDatee;
}
#property (strong,nonatomic) NSMutableArray *dataArray;
#property (strong,nonatomic) NSMutableDictionary *dataDictionary;
- (void) generateRandomDataForStartDate:(NSDate*)start endDate:(NSDate*)end;
#end
.m
#import "CalendarMonthViewController.h"
#import "AppDelegate.h"
#implementation CalendarMonthViewController
#pragma mark - View Lifecycle
- (void) viewDidLoad{
[super viewDidLoad];
[self.monthView selectDate:[NSDate month]];
}
-(void)viewWillAppear:(BOOL)animated{
[self updateTableOffset:YES];
NSLog(#"hi ha ");
}
-(void)fatchAllEvent{
eventStore = [[EKEventStore alloc] init];
if ([eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)])
{
__block typeof (self) weakSelf = self; // replace __block with __weak if you are using ARC
dispatch_async(dispatch_get_main_queue(), ^{
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
if (granted)
{
NSLog(#" granted");
[weakSelf performSelectorOnMainThread:#selector(allCalendarEvent) withObject:nil waitUntilDone:YES];
}
else
{
NSLog(#"Not granted");
}
}];
});
}
else
{
[self allCalendarEvent];
}
}
-(void)allCalendarEvent{
NSDate *startDate = [NSDate distantPast];
NSDate *endDate = [NSDate distantFuture];
// use Dictionary for remove duplicates produced by events covered more one year segment
NSMutableDictionary *eventsDict = [NSMutableDictionary dictionaryWithCapacity:1024];
NSDate* currentStart = [NSDate dateWithTimeInterval:0 sinceDate:startDate];
int seconds_in_year = 60*60*24*365;
// enumerate events by one year segment because iOS do not support predicate longer than 4 year !
while ([currentStart compare:endDate] == NSOrderedAscending) {
NSDate* currentFinish = [NSDate dateWithTimeInterval:seconds_in_year sinceDate:currentStart];
if ([currentFinish compare:endDate] == NSOrderedDescending) {
currentFinish = [NSDate dateWithTimeInterval:0 sinceDate:endDate];
}
NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:currentStart endDate:currentFinish calendars:nil];
[eventStore enumerateEventsMatchingPredicate:predicate
usingBlock:^(EKEvent *event, BOOL *stop) {
if (event) {
[eventsDict setObject:event forKey:event.eventIdentifier];
}
}];
currentStart = [NSDate dateWithTimeInterval:(seconds_in_year + 1) sinceDate:currentStart];
}
events = [[NSMutableArray alloc]init];
for (id key in eventsDict) {
id anObject = [eventsDict objectForKey:key];
[events addObject:anObject];
/* Do something with anObject. */
}
NSLog(#"all event %#",events);
CFRunLoopStop(CFRunLoopGetCurrent());
// NSLog(#"all event crash%#",events);
}
#pragma mark - MonthView Delegate & DataSource
- (NSArray*) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate{
if (!events) {
[self fatchAllEvent];
CFRunLoopRun();
}
NSLog(#"all event %#",events);
[self generateRandomDataForStartDate:startDate endDate:lastDate];
// NSLog(#"%#",self.dataDictionary);
NSLog(#"%#",self.dataArray);
NSLog(#"%#",self.dataDictionary);
NSLog(#"%#",[self.dataDictionary allKeys]);
return self.dataArray;
}
- (void) calendarMonthView:(TKCalendarMonthView*)monthView didSelectDate:(NSDate*)date{
// CHANGE THE DATE TO YOUR TIMEZONE
TKDateInformation info = [date dateInformationWithTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *myTimeZoneDay = [NSDate dateFromDateInformation:info timeZone:[NSTimeZone systemTimeZone]];
NSLog(#"Date Selected: %#",myTimeZoneDay);
[self.tableView reloadData];
}
- (void) calendarMonthView:(TKCalendarMonthView*)mv monthDidChange:(NSDate*)d animated:(BOOL)animated{
[super calendarMonthView:mv monthDidChange:d animated:animated];
[self.tableView reloadData];
}
#pragma mark - UITableView Delegate & DataSource
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if ([[UIDevice currentDevice] userInterfaceIdiom]==UIUserInterfaceIdiomPad)
{
NSArray *views =[[NSBundle mainBundle] loadNibNamed:#"CalendarTableHeader" owner:nil options:nil];
UIView *headerView=[views objectAtIndex:0];
return headerView;
}
else
{
return nil;
}
}
- (CGFloat) tableView:(UITableView *) tableView heightForHeaderInSection:(NSInteger) section {
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
return 25;
} else {
return 0;
}
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *ar = [self.dataDictionary objectForKey:[self.monthView dateSelected]];
if(ar == nil) return 0;
return [ar count];
}
- (UITableViewCell *) tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
NSArray *ar = [self.dataDictionary objectForKey:[self.monthView dateSelected]];
cell.textLabel.text = [ar objectAtIndex:indexPath.row];
return cell;
}
- (BOOL)isDate:(NSDate *)date inRangeFirstDate:(NSDate *)firstDate lastDate:(NSDate *)lastDate {
return [date compare:firstDate] == NSOrderedDescending &&
[date compare:lastDate] == NSOrderedAscending;
}
- (void) generateRandomDataForStartDate:(NSDate*)start endDate:(NSDate*)end{
// this function sets up dataArray & dataDictionary
// dataArray: has boolean markers for each day to pass to the calendar view (via the delegate function)
// dataDictionary: has items that are associated with date keys (for tableview)
NSMutableArray *arrayOfDates = [[NSMutableArray alloc ]init];
NSMutableArray *arrayOfNames = [[NSMutableArray alloc ]init];
// NSLog(#"Delegate Range: %# %# %d",start,end,[start daysBetweenDate:end]);
NSDateFormatter *newformater=[[[NSDateFormatter alloc]init]autorelease];
[newformater setDateFormat:#"yyyy-MM-dd HH:mm:ss "];
NSDate *startD = [newformater dateFromString:[newformater stringFromDate:start]];
NSDate *endD = [newformater dateFromString:[newformater stringFromDate:end]];
NSLog(#"%#",events);
BOOL isAttempt = NO;
for (int i =0; i<arrayOfDates.count; i++) {
if ([start isEqualToDate:[arrayOfDates objectAtIndex:i]]) {
[self.dataDictionary setObject:[NSArray arrayWithObjects:[arrayOfNames objectAtIndex:i],nil] forKey:start];
[self.dataArray addObject:[NSNumber numberWithBool:YES]];
isAttempt = YES;
}
else{
isAttempt = NO;
}
}
if (!isAttempt) {
[self.dataArray addObject:[NSNumber numberWithBool:NO]];
}
for (int i = 0; i<events.count; i++) {
NSDate *eventDate = [[events valueForKey:#"startDate"] objectAtIndex:i];
NSString *eventName = [[events valueForKey:#"title"]objectAtIndex:i];
NSLog(#"startreal%#",start);
NSLog(#"endreal%#",end);
NSLog(#"eventName:::%#",eventName);
NSLog(#"start%#",startD);
NSLog(#"end%#",endD);
NSLog(#"eventDate%#",eventDate);
if([self isDate:eventDate inRangeFirstDate:startD lastDate:endD]){
[arrayOfDates addObject:eventDate];
[arrayOfNames addObject:eventName];
}else{
}
}
NSLog(#"eventdate = %#",arrayOfDates);
NSLog(#"eventName = %#",arrayOfNames);
// the dates that we have will go thorought for loop and we wil check if its between start and end date then we will add that object to datadictionary or wont
[self.dataArray removeAllObjects];
[self.dataDictionary removeAllObjects];
self.dataArray = [NSMutableArray array];
self.dataDictionary = [NSMutableDictionary dictionary];
NSDate *d = start;
while(YES){
BOOL isAttempt = NO;
for (int i =0; i<arrayOfDates.count; i++) {
if ([d isEqualToDate:[arrayOfDates objectAtIndex:i]]) {
[self.dataDictionary setObject:[NSArray arrayWithObjects:[arrayOfNames objectAtIndex:i],nil] forKey:d];
[self.dataArray addObject:[NSNumber numberWithBool:YES]];
isAttempt = YES;
}
else{
isAttempt = NO;
}
}
if (!isAttempt) {
[self.dataArray addObject:[NSNumber numberWithBool:NO]];
}
TKDateInformation info = [d dateInformationWithTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
info.day++;
d = [NSDate dateFromDateInformation:info timeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
if([d compare:end]==NSOrderedDescending) break;
}
}
-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[self updateTableOffset:YES];
}
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
#end

uitviewcontroller with uitableview and custom uitableviewcells with uitextfields scroll up/down with keyboard

I am having some difficulty figuring out the best way to get my uitextfields to not be hidden when the keyboard popsup. Right now i have a UIView that contains a uitableview subview and button.
*The tableview that is inside the uiview is actually a uiviewcontroller with a programatically created tableivew, so it is not controlled by a uitableviewcontroller.
I have done research and i think i would need a scrollview then add the view to the scrollview and work on some scrolling when a specific textfield is selected and is hidden with the keyboard up scroll it up.
Is this a good approach ?
UPDATE:
I have two seperate Viewcontrollers. For-example let say MainViewcontroller and SecondViewcontroller. The secondviewcontroller has a uitableview in it. The cells inside of the tableview have textboxes which store user information(like a form). Then what i did was created an object of secondviewcontroller inside of mainviewcontroller. I did this becuause i need to have a "Next Button" at the bottom of the view. When I select a field where it would be located underneith the keyboard when it pops up i would like to have it scroll up and when closed it will go down. I had to use an object of uitableview because the Mainviewcontroller class would be way to big.(Please correct me if i am wrong). Thanks for the reply.
Here is a screenshot of what i am trying to do...
FUll UIView: http://postimage.org/image/puzdwpj3t/
With Keyboard open: http://postimage.org/image/g5nkwzwpd/
//Here is some code:
1. The first class here is for instance SecondViewcontroller.
2. The second section of code is for instance the mainviewcontroller, which creates an object of secondviewcontroller.
The below uiviewcontroller will create a table with 3 sections. Each cell has a textfield(except the middle, it is a button which pulls up a uipickerview). This is not a full class i only took the areas where the table is created.
-(void)viewDidLoad{
[super viewDidLoad];
// scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 300, 500)];
// scrollview.pagingEnabled = YES;
//
// //[scrollview addSubview:self.view];
// [self.view addSubview:scrollview];
table.scrollEnabled = YES;
dataArray = [[NSMutableArray alloc] init];
titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 290, 30)];
//dropper
titleField = [[UITextField alloc] initWithFrame:CGRectMake(10, 2, 300, 30)];
titleField.layer.cornerRadius = 8;
titleField.backgroundColor = [UIColor clearColor];
NSArray *firstItemsArray = [[NSArray alloc] initWithObjects:#"1",#"2", nil];
NSDictionary *firstItemsArrayDict = [NSDictionary dictionaryWithObject:firstItemsArray forKey:#"data"];
[dataArray addObject:firstItemsArrayDict];
//Second section dat
NSArray *secondItemsArray = [[NSArray alloc] initWithObjects:#"1", nil];
NSDictionary *secondItemsArrayDict = [NSDictionary dictionaryWithObject:secondItemsArray forKey:#"data"];
[dataArray addObject:secondItemsArrayDict];
NSArray *thirdItemsArray = [[NSArray alloc] initWithObjects:#"1",#"2",#"3", nil];
NSDictionary *thirdItemsArrayDict = [NSDictionary dictionaryWithObject:thirdItemsArray forKey:#"data"];
[dataArray addObject:thirdItemsArrayDict];
NSLog(#"the dataArray%#",dataArray);
if([self connectedToNetwork]){
dispatch_async(kBgQueue, ^{
//build the url of strings
FULLURL = [SERVERNAME stringByAppendingFormat:TitleLink];
//create the url
NSURL *url = [[NSURL alloc] initWithString:FULLURL];
//NSLog(#"here title url%#",url);
//get the data from the url
NSData* data = [NSData dataWithContentsOfURL: url];
//NSLog(#"here%#",data);
//get the data from the url
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
// NSLog(#"titleid:%#",TITLEID);
// NSLog(#"title categories:%#",titlecategories);
});
[table setBounces:NO];
}else{
dispatch_async(dispatch_get_main_queue(), ^ {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Please Check your internet connection"
message:#"Enable your internet connection"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
});
}
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return [dataArray count];
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
//Number of rows it should expect should be based on the section
NSDictionary *dictionary = [dataArray objectAtIndex:section];
NSArray *array = [dictionary objectForKey:#"data"];
return [array count];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.section == 1){
cell.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:#"longdropper300.png"]];
}
else{
cell.backgroundColor = [UIColor whiteColor];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
textField = [[UITextField alloc] initWithFrame:CGRectMake(15, 10, 290, 30)];
static NSString *cellValue = #"Cell";
UITableViewCell *cell =nil;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellValue];
}
cell.selectionStyle = UITableViewCellSelectionStyleGray;
if ([indexPath section] == 0) {
//cellValue=[items objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle= UITableViewCellSelectionStyleNone;
//textField.tag = 1;
textField.adjustsFontSizeToFitWidth = YES;
textField.textColor = [UIColor blackColor];
if(indexPath.section == 0){
//textfield for email
if ([indexPath row] == 0) {
textField.tag = 1;
textField.text = EMAIL;
textField.textColor= [UIColor blackColor];
textField.placeholder = #"Email: example#gmail.com";
textField.keyboardType = UIKeyboardTypeEmailAddress;
textField.returnKeyType = UIReturnKeyNext;
}
//textfield for phone number
else {
textField.tag = 2;
if ([PHONENUMBER isEqual: [NSNull null]] && PHONENUMBER == nil && PHONENUMBER == NULL && [PHONENUMBER isEqual: #""]){
NSLog(#"phone is empty%#",PHONENUMBER);
//[PHONENUMBER isEqual:#"frank"];
}else{
NSLog(#"phone is not empty%#",PHONENUMBER);
textField.text = PHONENUMBER;
}
textField.placeholder = #"Phone: xxx-xxx-xxxx";
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.secureTextEntry = NO;
}
textField.backgroundColor = [UIColor whiteColor];
textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
textField.textAlignment = UITextAlignmentLeft;
textField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[textField setEnabled: YES];
textField.delegate = self;
[cell addSubview:textField];
}
}
if(indexPath.section == 1){
[titleField setTextColor:[UIColor whiteColor]];
titleField.tag = 3;
titleField.placeholder = #"Select Contact Title";
titleField.returnKeyType = UIReturnKeyNext;
//titleField == textField.tag = 3;
if ([TITLENAME isEqual: [NSNull null]]){
NSLog(#"titlename is empty%#",TITLENAME);
}else{
NSLog(#"titlename is not empty%#",TITLENAME);
titleField.text = TITLENAME;
}
titleField.keyboardType = UIKeyboardTypeDefault;
titleField.returnKeyType = UIReturnKeyDone;
titleField.secureTextEntry = NO;
titleField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
titleField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
titleField.textAlignment = UITextAlignmentCenter;
titleField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[titleField setEnabled: NO];
titleField.delegate = self;
[cell addSubview:titleField];
NSLog(#"here is the titlename%#",TITLENAME);
}
if(indexPath.section == 2){
if ([indexPath row] == 0) {
textField.tag = 4;
textField.placeholder = #"First Name";
cell.selectionStyle= UITableViewCellSelectionStyleNone;
if ([FIRSTNAME isEqual: [NSNull null]]){
NSLog(#"firstname is empty%#",FIRSTNAME);
textField.text = #"";
}else{
textField.text = FIRSTNAME;
}
textField.keyboardType = UIKeyboardTypeEmailAddress;
textField.returnKeyType = UIReturnKeyNext;
}
if([indexPath row] == 1){
textField.tag = 5;
textField.placeholder = #"Last Name";
if ([LASTNAME isEqual: [NSNull null]]){
NSLog(#"lastname is empty%#",LASTNAME);
textField.text = #"";
}else{
textField.text = LASTNAME;
}
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyNext;
//textField.secureTextEntry = NO;
}
if([indexPath row] == 2){
textField.tag = 6;
textField.placeholder = #"Company";
if ([COMPANY isEqual: [NSNull null]]){
NSLog(#"company is empty%#",COMPANY);
textField.text = #"";
}
else{
textField.text = COMPANY;
}
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.secureTextEntry = NO;
}
//]textField.backgroundColor = [UIColor whiteColor];
textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
textField.textAlignment = UITextAlignmentLeft;
textField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[textField setEnabled: YES];
textField.delegate = self;
[cell addSubview:textField];
}
return cell;
}
//Change the Height of title cell drop down
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
if (indexPath.section == 1) {
if (indexPath.row == 0) {
return 30;
}
}
return 45;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
if(([textField tag] == 1)){
NSString *emailRegEx = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
//Valid email address
if ([emailTest evaluateWithObject:textField.text] == YES)
{
EMAIL = [textField.text copy];
NSLog(#"here is the email%#",EMAIL);
}
else
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Bad Email"
message: #"Please Re-enter the email address with a valid email"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
textField.text = nil;
NSLog(#"email not in proper format");
}
}
if(([textField tag] == 2)){
NSString *phoneRegex = #"[235689][0-9]{6}([0-9]{3})?";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", phoneRegex];
//valid email address
if ([phoneTest evaluateWithObject:textField.text] == YES)
{
PHONENUMBER = [textField.text copy];
NSLog(#"here is the phone number %#",PHONENUMBER);
}
else
{
NSLog(#"Phone Number Invalid");
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"xxx-xxx-xxxx"
message: #"Please enter a valid phone number"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
textField.text = nil;
}
}
if(([textField tag] == 4)){
FIRSTNAME = [textField.text copy];
NSLog(#"here is the firstName%#",FIRSTNAME);
}
if(([textField tag] == 5)){
LASTNAME = [textField.text copy];
NSLog(#"here is the Last Name%#",LASTNAME);
}
if(([textField tag] == 6)){
COMPANY = [textField.text copy];
NSLog(#"here is the Company%#",COMPANY);
}
return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
Main View Controller
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)addMyButton{ // Method for creating button, with background image and other properties
loginButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
loginButton.frame = CGRectMake(10.0,130.0, 300.0, 40.0);
[loginButton setTitle:#"Login" forState:UIControlStateNormal];
loginButton.backgroundColor = [UIColor clearColor];
[loginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal ];
UIImage *buttonImageNormal = [UIImage imageNamed:#"blueButton.png"];
UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[loginButton setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
UIImage *buttonImagePressed = [UIImage imageNamed:#"whiteButton.png"];
UIImage *strechableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[loginButton setBackgroundImage:strechableButtonImagePressed forState:UIControlStateHighlighted];
[self.view addSubview:loginButton];
[loginButton addTarget: self
action: #selector(loginButtonClicked:)
forControlEvents: UIControlEventTouchUpInside];
}
//Change the View and send the information to the servlet once login is clicked.
- (void)loginButtonClicked: (id)sender{
loginButton.enabled = NO;
activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(20, 60, 20, 20)];
UIBarButtonItem * barButton = [[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
[self navigationItem].rightBarButtonItem = barButton;
[activityIndicator startAnimating];
[passwordTF resignFirstResponder];
//start new thread
//dispatch_async(kBgQueue, ^{
NSLog(#"Username:%#",USERNAME);
NSLog(#"Password:%#",PASSWORD);
NSLog(#"COMPANYID: %#", COMPANYID);
//NSLog(#"LOGINID: %#", LOGINID);
if((USERNAME == NULL) || (USERNAME == nil) || ([USERNAME isEqualToString:#""])){
//NSLog(#"null password or usernaem");
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Username or password not found"
message:#"please try again"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[activityIndicator stopAnimating];
// MangoLoginViewController *SenderInfoViews = [[MangoLoginViewController alloc] init];
// [self.navigationController pushViewController:SenderInfoViews animated:NO];
}else if((PASSWORD == NULL) || (PASSWORD == nil) || ([PASSWORD isEqualToString:#""])){
//NSLog(#"null password or usernaem");
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Username or password not found"
message:#"please try again"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[activityIndicator stopAnimating];
// MangoLoginViewController *SenderInfoViews = [[MangoLoginViewController alloc] init];
// [self.navigationController pushViewController:SenderInfoViews animated:NO];
}else{
//NSLog(#"all good");
NSLog(#"Login button clicked, load the next view and check for password");
NSLog(#"full the url%#",FULLURL);
//build the url of strings
FULLURL = ******
if([self connectedToNetwork])
{
dispatch_queue_t downloadQueue = dispatch_queue_create("data loader", NULL);
dispatch_async(downloadQueue, ^{
//create the url
NSURL *url = [[NSURL alloc] initWithString:FULLURL];
NSLog(#"here%#",url);
//get the data from the url
NSData* data = [NSData dataWithContentsOfURL: url];
NSLog(#"here%#",data);
NSLog(#"here that data%#",data);
if(data != nil){
//
//get the data from the url
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
//
NSLog(#"hello Username:%#",USERNAME);
NSLog(#"Password:%#",PASSWORD);
NSLog(#"h4llo COMPANYID: %#", COMPANYID);
NSLog(#"LOGINID: %#", LOGINID);
//
// // [self performSelectorOnMainThread:#selector(checkLogin:) withObject:LOGINID waitUntilDone:YES];
//
//
#try {
//NSLog(#"before loginddd %#",LOGINID);
if(COMPANYID != 0){
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:USERNAME forKey:#"UserName"];
[prefs setObject:#"Pass" forKey:#"Pass"];
// This is suggested to synch prefs, but is not needed
[prefs synchronize];
NSLog(#"here is the login identiy%#",LOGINID);
MangoContactSelection *SenderInfoViews = [[MangoContactSelection alloc] init];
[self.navigationController pushViewController:SenderInfoViews animated:NO];
}
else{
dispatch_async(dispatch_get_main_queue(), ^ {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"bad NAME"
message:#"GOO"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
// [self.view setNeedsDisplay];
[self.view reloadInputViews];
MangoLoginViewController *SenderInfoViews = [[MangoLoginViewController alloc] init];
[self.navigationController pushViewController:SenderInfoViews animated:NO];
[activityIndicator stopAnimating];
});
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Login Failed"
message:#"Bad"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
//[activityIndicator stopAnimating];
}
// if the data is nil do this
}else{
dispatch_async(dispatch_get_main_queue(), ^ {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"No Internet!"
message:#"Please Check your internet Connection"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[self.view setNeedsDisplay];
MangoLoginViewController *SenderInfoViews = [[MangoLoginViewController alloc] init];
[self.navigationController pushViewController:SenderInfoViews animated:NO];
});
}
dispatch_async(dispatch_get_main_queue(), ^ {
//UIImage *image = [UIImage imageWithData:imageData];
//[table reloadData];
//[actIndicator stopAnimating];
[self.view reloadInputViews];
[activityIndicator stopAnimating];
// sender because that's the element that called us by clicking refresh
});
});
}else{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"No Internet!"
message:#"Please Check your internet Connection"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[self.view setNeedsDisplay];
MangoLoginViewController *SenderInfoViews = [[MangoLoginViewController alloc] init];
[self.navigationController pushViewController:SenderInfoViews animated:NO];
}
}
[self.view reloadInputViews];
}//login
-(void)gobacktoContactCreate{
MangoContactSelection *gobackhome = [[MangoContactSelection alloc]init];
[self.navigationController pushViewController:gobackhome animated:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
//self.view setBackgroundColor:([UIColor blackColor]);
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *userName = [prefs stringForKey:#"UserName"];
//NSString *pass = [prefs stringForKey:#"Pass"];
//navigation bar
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
[self.navigationController setNavigationBarHidden: NO animated:NO];
self.navigationItem.hidesBackButton = YES;
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStylePlain target:nil action:#selector(gobacktoContactCreate)];
self.navigationItem.title=#"Login";
//User name text field................
usernameTF = [[UITextField alloc] initWithFrame:CGRectMake(10, 25, 300, 40)];
usernameTF.borderStyle = UITextBorderStyleRoundedRect;
usernameTF.font = [UIFont systemFontOfSize:15];
usernameTF.placeholder = #"Username";
usernameTF.text = userName;
usernameTF.autocorrectionType = UITextAutocorrectionTypeNo;
usernameTF.keyboardType = UIKeyboardTypeDefault;
usernameTF.returnKeyType = UIReturnKeyNext;
usernameTF.clearButtonMode = UITextFieldViewModeWhileEditing;
usernameTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
//User name text field................
passwordTF = [[UITextField alloc] initWithFrame:CGRectMake(10, 75, 300, 40)];
passwordTF.borderStyle = UITextBorderStyleRoundedRect;
passwordTF.font = [UIFont systemFontOfSize:15];
passwordTF.placeholder = #"Password";
passwordTF.autocorrectionType = UITextAutocorrectionTypeNo;
passwordTF.keyboardType = UIKeyboardTypeDefault;
passwordTF.returnKeyType = UIReturnKeyDone;
passwordTF.clearButtonMode = UITextFieldViewModeWhileEditing;
passwordTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
passwordTF.secureTextEntry = YES;
//create the clickable labels
//register link
registerLabel = [[UILabel alloc]initWithFrame:CGRectMake(150,170, 150, 20)];
registerLabel.text = #"Request an account";
registerLabel.font = [UIFont systemFontOfSize:12];
registerLabel.userInteractionEnabled = YES;
registerLabel.textColor = [UIColor blueColor];
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(requestRegistration:)];
[registerLabel addGestureRecognizer:gr];
gr.numberOfTapsRequired = 1;
gr.cancelsTouchesInView = NO;
//create the label for
registerText = [[UILabel alloc]initWithFrame:CGRectMake(60,170, 90, 20)];
registerText.text = #"New to *******?";
registerText.font = [UIFont systemFontOfSize:12];
// //forgot password link
// forgotPassword = [[UILabel alloc]initWithFrame:CGRectMake(210,190, 150, 20)];
// forgotPassword.font = [UIFont systemFontOfSize:12];
// forgotPassword.textColor = [UIColor blueColor];
// forgotPassword.text = #"Forgot Password?";
// forgotPassword.userInteractionEnabled = YES;
// UITapGestureRecognizer *tapRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(requestForgottenPassword:)];
// [registerLabel addGestureRecognizer:tapRec];
// tapRec.numberOfTapsRequired = 1;
// tapRec.cancelsTouchesInView = NO;
[self.view addSubview:passwordTF];
[self.view addSubview:usernameTF];
[self.view addSubview:registerLabel];
[self.view addSubview:registerText];
// [self.view addSubview:forgotPassword];
[self addMyButton];
usernameTF.delegate = self;
passwordTF.delegate = self;
}
-(void)requestRegistration:(UITapGestureRecognizer *)gr{
//for registration
NSLog(#"request registration link clicked");
}
-(void)requestNewPassword:(UITapGestureRecognizer *)tapRec{
//for registration
NSLog(#"request password link clicked");
}
//Grabs the Json from the servlet and then parses it for the username and password.
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
//NSLog(#"here is the login info from json: %#", json);
// NSString *FALSELOGIN;
COMPANYID = [json valueForKey:#"companyid"];
NSLog(#"COMPANY ID: %#", COMPANYID);
// LOGINID = [json valueForKey:#"login"];
// NSLog(#"LOGIN ID: %#", LOGINID);
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
if((textField = usernameTF)){
USERNAME = [textField.text copy];
//NSLog(#"here is the string for username;%#", USERNAME);
}
if((textField = passwordTF)){
PASSWORD = [textField.text copy];
//NSLog(#"here is the password guy %#",PASSWORD);
}
return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == usernameTF) {
[passwordTF becomeFirstResponder];
}
else{
[passwordTF resignFirstResponder];
}
return YES;
}
//- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//{
// [passwordTF resignFirstResponder];
//
//}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
You have added Tableview inside view of UIViewController. right?
In which view you have added UITextview.? View of UIViewController ??
You can add UITextView in UIView and by applying animation just change frame of UITextView.
Ex.
// Take View UP....
[UIView animationWithDuration:secs delay:0.0 option:option animation:^{
CGRect frame = textview.frame;
frame.origin.y = 10; // Change Y position of frame.
textview.frame = frame;
}
completion:nil];
// Take View down
[UIView animationWithDuration:secs delay:0.0 option:option animation:^{
CGRect frame = textview.frame;
frame.origin.y = 100; // Change Y position of frame.
textview.frame = frame;
}
completion:nil];
No need to take UIScrollView.
Dhaval, I beleive your solution would work, but I ended up finding exactly what i was looking for here:
http://www.youtube.com/watch?feature=player_detailpage&v=qSvDWnasJ9I
Thanks.

How can I search data from tableview cell?

I have an UITableview controller which representing fetched XML data. For representing these data I used five UILabel. Now I have to add a searchbar at the top of the UITableview. So programmatically I have added a searchbar.
Now I have used searching theorem for search data from the UITableview. But It is not working. I can search data from UItableview when only one text in the UItableviewcell without any UIlabel or something else but in my UItableviewcell cell are taking five UILabel that's why it's becoming tough for me to search data from the UItableviewcell. For understanding I am attaching my code how I am representing my XML data in tableview cell.
This is my XML data representation in UITableviewCell...
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:15.0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrow.png"]];
cell.accessoryView = imageView;
cell.accessoryType = UITableViewCellSelectionStyleNone;
tableView.separatorColor = [UIColor clearColor];
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
cellView = [[[UIView alloc] initWithFrame:CGRectMake(5,8,290, 120)] autorelease];
cellView.backgroundColor = [UIColor clearColor];
cellView.tag =10;
[cell.contentView addSubview:cellView];
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(2, 40, 48, 48)];
imgView.image = [UIImage imageNamed:#"productbox.png"];
imgView.layer.borderColor = [UIColor blackColor].CGColor;
imgView.layer.borderWidth = 2.0;
imgView.tag = 5;
[cellView addSubview:imgView];
CGRect idLabelRect = CGRectMake(65, 0, 190, 18);
idLabel = [[[UILabel alloc] initWithFrame:idLabelRect] autorelease];
idLabel.textAlignment = UITextAlignmentLeft;
idLabel.textColor = [UIColor blackColor];
idLabel.font = [UIFont systemFontOfSize:12];
idLabel.backgroundColor = [UIColor clearColor];
idLabel.layer.borderColor = [UIColor grayColor].CGColor;
idLabel.tag = 0;
CGRect statusRect = CGRectMake(65, 22, 190, 22);
statusLabel = [[[UILabel alloc] initWithFrame:statusRect] autorelease];
statusLabel.textAlignment = UITextAlignmentLeft;
statusLabel.textColor = [UIColor blackColor];
statusLabel.font = [UIFont systemFontOfSize:12];
statusLabel.backgroundColor = [UIColor clearColor];
statusLabel.layer.borderColor = [UIColor grayColor].CGColor;
statusLabel.tag = 1;
CGRect orderDateRect = CGRectMake(65, 48, 190, 22);
orderDate = [[[UILabel alloc] initWithFrame:orderDateRect] autorelease];
orderDate.textAlignment = UITextAlignmentLeft;
orderDate.textColor = [UIColor blackColor];
orderDate.font = [UIFont systemFontOfSize:12];
orderDate.backgroundColor = [UIColor clearColor];
orderDate.layer.borderColor = [UIColor grayColor].CGColor;
orderDate.tag = 2;
CGRect byRect = CGRectMake(65, 75, 190, 22);
byLabel = [[[UILabel alloc] initWithFrame:byRect] autorelease];
byLabel.textAlignment = UITextAlignmentLeft;
byLabel.textColor = [UIColor blackColor];
byLabel.font = [UIFont systemFontOfSize:12];
byLabel.backgroundColor = [UIColor clearColor];
byLabel.layer.borderColor = [UIColor grayColor].CGColor;
byLabel.tag = 3;
CGRect totalRect = CGRectMake(65, 98, 190, 22);
totalLabel = [[[UILabel alloc] initWithFrame:totalRect] autorelease];
totalLabel.textAlignment = UITextAlignmentLeft;
totalLabel.textColor = [UIColor blackColor];
totalLabel.font = [UIFont systemFontOfSize:12];
totalLabel.backgroundColor = [UIColor clearColor];
totalLabel.layer.borderColor = [UIColor grayColor].CGColor;
totalLabel.tag = 4;
[cellView addSubview:idLabel];
[cellView addSubview:statusLabel];
[cellView addSubview:orderDate];
[cellView addSubview:byLabel];
[cellView addSubview:totalLabel];
}
if(searching == YES){
//[cell setText:[tableData objectAtIndex:indexPath.row]];
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
}
else{
cellView = (UIView *)[cell.contentView viewWithTag:10];
idLabel = (UILabel *)[cellView viewWithTag:0];
statusLabel = (UILabel *)[cellView viewWithTag:1];
orderDate = (UILabel *)[cellView viewWithTag:2];
byLabel = (UILabel *)[cellView viewWithTag:3];
totalLabel = (UILabel *)[cellView viewWithTag:4];
imgView = (UIImageView *)[cellView viewWithTag:5];
if(pendingOrder == NO && todaysOrder == NO){
idLabel.text = [NSString stringWithFormat:#"Order Id: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:0]];
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:1]];
orderDate.text = [NSString stringWithFormat:#"Date: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:2]];
byLabel.text =[NSString stringWithFormat:#"By: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:3]];
totalLabel.text =[NSString stringWithFormat:#"Total: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:4]];
}
else if(pendingOrder == YES && todaysOrder == NO){
idLabel.text = [NSString stringWithFormat:#"Order Id: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:0]];
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:1]];
orderDate.text = [NSString stringWithFormat:#"Date: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:2]];
byLabel.text =[NSString stringWithFormat:#"By: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:3]];
totalLabel.text =[NSString stringWithFormat:#"Total: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:4]];
}
}
return cell;
}
And this searching Delegate.....
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
searching = YES;
// only show the status bar’s cancel button while in edit mode
sBar.showsCancelButton = YES;
sBar.autocorrectionType = UITextAutocorrectionTypeNo;
// flush the previous search content
[tableData removeAllObjects];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
searching = NO;
sBar.showsCancelButton = NO;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[tableData removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:#""] && searchText==nil){
[tableview reloadData];
return;
}
NSInteger counter = 0;
for(NSString *name in dataSource)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSRange r = [name rangeOfString:searchText];
if(r.location != NSNotFound)
{
if(r.location== 0)//that is we are checking only the start of the names.
{
[tableData addObject:name];
}
}
counter++;
[pool release];
}
[tableview reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
// if a valid search was entered but the user wanted to cancel, bring back the main list content
[tableData removeAllObjects];
searching = NO;
[tableData addObjectsFromArray:dataSource];
#try{
searching = NO;
[tableview reloadData];
}
#catch(NSException *e){
}
[sBar resignFirstResponder];
sBar.text = #"";
}
// called when Search (in our case “Done”) button pressed
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[sBar resignFirstResponder];
}
For more help to understand i am also attaching my viewDidLoad....
//Add the search bar
sBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,0,320,50)];
sBar.delegate = self;
searching = NO;
[self.view addSubview:sBar];
tableview.dataSource = self;
tableview.delegate = self;
//initialize the two arrays; datasource will be initialized and populated by appDelegate
searchData = [[NSMutableArray alloc] init];
tableData = [[NSMutableArray alloc] init];
[tableData addObjectsFromArray:dataSource];//on launch it should display all the records
Edit
This is my edited portion of numberOfSectionsInTableView and numberOfRowsInSection...
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if(searching == YES){
searching = NO;
sectionCount = [tableData count];
}
else {
if(pendingOrder == NO && todaysOrder == NO){
sectionCount = [records count];
NSLog(#"section cout: %d",sectionCount);
}
else if(pendingOrder == YES && todaysOrder == NO){
//Total pending order counting
sectionCount = [pendingRecords count];
NSLog(#"section cout for pending: %d",sectionCount);
}
else if(pendingOrder == NO && todaysOrder == YES){
NSLog(#"todays order number counting");
}
}
return sectionCount;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
Try this:-
copylistofItem is NSMutableArray copying data that matched with search bar criteria.
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
int i=0
for (NSString *str in [records objectAtIndex:indexPath.i] objectAtIndex:0])
{
[searchArray addObject:str];
i++;
}
for (NSString *sTemp in searchArray)
{
NSString *txtToSearch =[[NSString alloc] initWithString:[sTemp substringWithRange:NSMakeRange(0,[searchText length])]];
if([[txtToSearch lowercaseString] isEqualToString:[searchText lowercaseString]])
{
[copyListOfItems addObject:sTemp];
}
}
[searchArray release];
searchArray = nil;
}
Also we want to know what you have written in your numberOfSections tableView Delegate.

Crash after returning to tableview

So I am writing an app to read an rss feed, and display the contents in a tableview. It also lets the user play back mp3s that it finds for each item. Anyway the app seemed to be running fine before I started adding new views. Now every time I come back from a view and scroll around a bit, I get "Program received signal "SIGABRT"" or something similar.
here's most of the program:
- (IBAction)playAction:(id)sender
{
// Get row
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *buttonCell =
(UITableViewCell *) [[senderButton superview] superview];
NSInteger buttonRow = [[self.tableView
indexPathForCell:buttonCell] row];
// Entry for row
RSSEntry *senderEntry = [_allEntries objectAtIndex:buttonRow];
// This is where _allEntries gets filled
- (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 parseRss:doc.rootElement entries:entries];
if ([_allEntries count] > 0) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// Update
int i=0;
while (![[[_allEntries objectAtIndex:i] articleUrl] isEqualToString:[[entries objectAtIndex:i] articleUrl]])
{
[_allEntries insertObject:[entries objectAtIndex:i] atIndex:0];
i++;
}
[self.tableView reloadData];
}];
}
else
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries)
{
[_allEntries addObject:entry];
}
NSLog(#"entries:%d", [_allEntries count]);
[self.tableView reloadData];
}];
}
}
}];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"View did load");
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refreshButton:)];
pauseImage = [UIImage imageNamed:#"pause_circle_small.png"];
playImage = [UIImage imageNamed:#"play_circle_small.png"];
player = nil;
isPlaying = NO;
self.title = #"Feed";
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feed = [[NSString alloc] initWithString:#"http://site.org/rss/"];
[self refresh];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [_allEntries count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UILabel *mainLabel, *secondLabel;
UIButton *playBtn;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(42.0, 5.0, 250.0, 20.0)] autorelease];
mainLabel.tag = MAINLABEL_TAG;
mainLabel.font = [UIFont fontWithName:#"Arial-BoldMT" size:18.0];
mainLabel.textAlignment = UITextAlignmentLeft;
mainLabel.textColor = [UIColor blackColor];
mainLabel.highlightedTextColor = [UIColor whiteColor];
[cell.contentView addSubview:mainLabel];
secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(42.0, 27.0, 250.0, 15.0)] autorelease];
secondLabel.tag = SECONDLABEL_TAG;
secondLabel.font = [UIFont fontWithName:#"ArialMT" size:14.0];
secondLabel.textAlignment = UITextAlignmentLeft;
secondLabel.textColor = [UIColor colorWithRed:222.0/255.0 green:95.0/255.0
blue:199.0/255.0 alpha:1.0];
secondLabel.highlightedTextColor = [UIColor whiteColor];
[cell.contentView addSubview:secondLabel];
playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
playBtn.tag = PLAYBTN_TAG;
playBtn.frame = CGRectMake(2.0, 6.0, playImage.size.width, playImage.size.height);
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
//[playBtn setBackgroundImage:playImage forState:UIControlStateHighlighted];
[playBtn addTarget:self action:#selector(playTapped:)
forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:playBtn];
}
else
{
mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
playBtn = (UIButton *)[cell.contentView viewWithTag:PLAYBTN_TAG];
}
// Alternate bg color
if (indexPath.row%2 == 0) {
UIColor *altColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0
blue:230.0/255.0 alpha:1];
mainLabel.backgroundColor = altColor;
secondLabel.backgroundColor = altColor;
}
else
{
UIColor *altColor = [UIColor colorWithRed:255.0 green:255.0
blue:255.0 alpha:1];
mainLabel.backgroundColor = altColor;
secondLabel.backgroundColor = altColor;
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSLog(#"Entry: %#", entry);
// Manage play button
if (entry == currEntry)
{
if(isPlaying)
{
[playBtn setBackgroundImage:pauseImage forState:UIControlStateNormal];
}
else
{
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
}
}
else
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
mainLabel.text = entry.articleTitle;
secondLabel.text = entry.articleArtist;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
DetailView *detailViewController = [[DetailView alloc] initWithNibName:#"DetailedView" bundle:[NSBundle mainBundle]];
RSSEntry *entry = [_allEntries objectAtIndex:[indexPath row]];
[self.navigationController pushViewController:detailViewController animated:YES];
detailViewController.songTitle.text = entry.articleTitle;
detailViewController.artistName.text = entry.articleArtist;
[entry release];
[detailViewController release];
}
- (void)dealloc
{
[player release];
player = nil;
[_queue release];
_queue = nil;
[_feed release];
_feed = nil;
[_allEntries release];
_allEntries = nil;
[super dealloc];
}
#end
Please Dont release any #synthesize variable. You should only release it in dealloc method
It's a wild guess, but you don't retain the images that you get in viewDidLoad:
pauseImage = [UIImage imageNamed:#"pause_circle_small.png"];
playImage = [UIImage imageNamed:#"play_circle_small.png"];
Either use retaining property and dot syntax or send each a retain.
AHAA!!! I was setting my RSSEntry to autorelease before putting them in the _allEntries array. They were getting dealloc'd when I changed views. Don't do that. Thanks for the help everyone. That was so simple, I feel dumb now.
please don't release the self.feed and also when unload or dealloc the view at that time put delegate nil means
tableview.delegate = nil;
this one is the main thing check after this i think u don't nil the delegate of tableview.
without line where you get crash its hard to tell, but most likely you accessing some object what was dealloc'ed
most likely its here
self.feed = [[NSString alloc] initWithString:#"http://site.org/rss/music"];
[self.feed release];
you releasing objects right away, but its hard to tell without knowing if you have retained property

iphone Dev - activity indicator with NSThread not working on Nav controller table view

I really can't get this to work, basically when my JSON feeds loads I want the indicator to show, then hide when it's stopped.
It loads top level menu items 1st "Publishing, Broadcasting, Marketing Services", then when Broadcasting is selected it loads a feed using the JSON framework hosted on Google. Round this load I call startIndicator and stopIndicator using the NSThread. Have I missed something?
#implementation GeneralNewsTableViewController
#synthesize dataList;
#synthesize generalNewsDetailViewController;
#synthesize atLevel;
-(void) startIndicator
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc ] init ];
[(UIActivityIndicatorView *)[self navigationItem].rightBarButtonItem.customView startAnimating];
[pool release];
}
-(void) stopIndicator
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc ] init ];
[(UIActivityIndicatorView *)[self navigationItem].rightBarButtonItem.customView stopAnimating];
[pool release];
}
- (void)viewDidLoad {
NSMutableArray *checker = self.dataList;
if(checker == nil)
{
self.title = NSLocalizedString(#"General1",#"General News");
NSMutableArray *array = [[NSArray alloc] initWithObjects:#"Publishing", #"Broadcasting",#"Marketing Services",nil];
self.dataList = [array retain];
self.atLevel = #"level1";
[array release];
}
UIActivityIndicatorView * activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
//set the initial property
[activityIndicator stopAnimating];
[activityIndicator hidesWhenStopped];
//Create an instance of Bar button item with custome view which is of activity indicator
UIBarButtonItem * barButton = [[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
//Set the bar button the navigation bar
[self navigationItem].rightBarButtonItem = barButton;
//Memory clean up
[activityIndicator release];
[barButton release];
[super viewDidLoad];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *level = self.atLevel;
if([level isEqualToString:#"level2"])
{
return 70.0f;
}
else
{
return 40.0f;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *FirstLevelCell = #"FirstLevelCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:FirstLevelCell];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:FirstLevelCell] autorelease];
}
NSInteger row = [indexPath row];
NSString *level = self.atLevel;
if([level isEqualToString:#"level2"])
{
NSMutableArray *stream = [self.dataList objectAtIndex:row];
NSString *newsTitle = [stream valueForKey:#"title"];
if( ![newsTitle isKindOfClass:[NSString class]] )
{
cell.textLabel.text = #"";
}
else
{
cell.textLabel.text = [stream valueForKey:#"title"];
}
cell.textLabel.numberOfLines = 2;
cell.textLabel.font =[UIFont systemFontOfSize:10];
cell.detailTextLabel.numberOfLines = 1;
cell.detailTextLabel.font= [UIFont systemFontOfSize:8];
cell.detailTextLabel.text = [stream valueForKey:#"created"];
NSData *imageURL = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.website.co.uk/images/stories/img.jpg"]];
UIImage *newsImage = [[UIImage alloc] initWithData:imageURL];
cell.imageView.image = newsImage;
[imageURL release];
[newsImage release];
}
else
{
cell.textLabel.text = [dataList objectAtIndex:row];
}
return cell;
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
NSMutableString *levelType = (NSMutableString *) [dataList objectAtIndex:row];
if(![levelType isKindOfClass:[NSString class]])
{
if(self.generalNewsDetailViewController == nil)
{
GeneralNewsDetailViewController *generalDetail = [[GeneralNewsDetailViewController alloc] initWithNibName:#"GeneralNewsDetailView" bundle:nil];
self.generalNewsDetailViewController = generalDetail;
[generalDetail release];
}
NSDictionary *stream = [self.dataList objectAtIndex:row];
NSString *newsTitle = [stream valueForKey:#"title"];
if( ![newsTitle isKindOfClass:[NSString class]] )
{
generalNewsDetailViewController.newsTitle = #"";
}
else
{
generalNewsDetailViewController.newsTitle =[stream valueForKey:#"title"];
}
generalNewsDetailViewController.newsId = [stream valueForKey:#"id"];
generalNewsDetailViewController.fullText = [stream valueForKey:#"fulltext"];
generalNewsDetailViewController.newsImage = [stream valueForKey:#"images"];
generalNewsDetailViewController.created = [stream valueForKey:#"created"];
HowDo_v1AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
[delegate.generalNewsNavController pushViewController:self.generalNewsDetailViewController animated:YES];
}
else
{
GeneralNewsTableViewController
*generalSubDetail = [[GeneralNewsTableViewController alloc] initWithNibName:#"GeneralNewsTableView" bundle:nil];
NSMutableArray *array;
NSString *titleSelected = (NSString *) [dataList objectAtIndex:row];
if([titleSelected isEqualToString:#"Publishing"])
{
generalSubDetail.title = #"Publishing news detail";
array = [[NSArray alloc] initWithObjects:#"pub News1", #"pub News2",#"pub News3",nil];
generalSubDetail.atLevel = #"level1";
}
else if ([titleSelected isEqualToString:#"Broadcasting"])
{
generalSubDetail.title = #"Broadcasting news detail";
/// START
[self performSelectorOnMainThread:#selector(startIndicator) withObject:nil waitUntilDone:YES];
if(jSONDataAccessWrapper == nil)
{
jSONDataAccessWrapper = [JSON_DataAccess_Wrapper alloc];
}
array = [jSONDataAccessWrapper downloadJSONFeed];
[self performSelectorOnMainThread:#selector(stopIndicator) withObject:nil waitUntilDone:YES];
generalSubDetail.atLevel = #"level2";
}
else if ([titleSelected isEqualToString:#"Marketing Services"])
{
generalSubDetail.title = #"Marketing Services news detail";
array = [[NSArray alloc] initWithObjects:#"Marketing News1", #"Marketing News2",#"Marketing News3",nil];
generalSubDetail.atLevel = #"level1";
}
generalSubDetail.dataList = array;
[self.navigationController pushViewController:generalSubDetail animated:YES];
[titleSelected release];
}
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
//- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSIndexPath *) section
{
return [self.dataList count];
}
Cheers for any feedback
Frames
It is usually recommended by Apple that operations on user interface should be done on the main thread.
What you can do is to defer the callback into the main thread:
- (void)startIndicator
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self performSelectorOnMainThread:#selector(startAnimating:) withObject:nil waitUntilDone:NO];
[pool release];
}
- (void)startAnimating:(id)sender
{
[(UIActivityIndicatorView *)[self navigationItem].rightBarButtonItem.customView startAnimating];
}
Check out the Thread Guide from Apple. It contains useful information.