SDWebImage Library is not working? - ios

I used SDWebImage library to download images from server. In my code I am facing an image loading issue & SDwebImage. The problem is: I've written the code like this:
[cell.imgNews setImageWithURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]]
If I give I like this my Application is working smooth & fast. But the images are not loading. It's displaying only empty cells. The Reason of displaying the empty cell is a couple of images are named in Arabic and in that the names are having space Ex.%20.
My question is: how can we display the Arabic named images (you can see the bellow screen shot) in the image cell? (Note: Few images are being displayed that are named in English)
But the Images are downloading in the Debugger Area (You can see the Screen shot here)
To Escape that empty cell I used this code:
[cell.imgNews setImageWithURL:[NSURL URLWithString:[[self.arrImages objectAtIndex:indexPath.row] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
The Problem is if I use this code, the application gets very slow. How can I solve this Issue?
Can any one help me to solve this issue?
Here is my Code :
NewsViewController.m
#import "NewsViewController.h"
#import "NewsTableViewCell.h"
#import "NewDetailsViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "SearchVC.h"
#interface NewsViewController ()
{
NSString *temString;
NSMutableString *strTemp;
BOOL isDateSearch;
int search;
}
#property(strong,nonatomic) NSArray *SearchResultsArray;
#end
#implementation NewsViewController
#synthesize arrImages;
#synthesize TittleOne;
#synthesize TittleTwo;
#synthesize TittleThree;
#synthesize datepicker;
#synthesize PickerContainer;
#synthesize datepickerTittle;
#synthesize searchBr;
#synthesize NewsIndicator;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
#pragma mark - View Life Cycle
- (void)viewDidLoad
{
[self performSelector:#selector(myindicator) withObject:nil afterDelay:10.0];
[super viewDidLoad];
search=0;
self.searchBr.hidden=YES;
self.searchBr.barTintColor = UIColorFromRGB(0Xe54c41);
self.searchBr.backgroundColor = UIColorFromRGB(0Xe54c41);
[self removeUISearchBarBackgroundInViewHierarchy:self.searchDisplayController.searchBar];
self.searchDisplayController.searchBar.backgroundColor = NO;
[TittleOne setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
[TittleTwo setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
[TittleThree setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:10]];
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSLog(#"%#",[dateFormatter stringFromDate:[NSDate date]]);
[TittleTwo setText:[dateFormatter stringFromDate:[NSDate date]]];
// [[UIColor redColor] set];
[datepickerTittle setFont:[UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
// [datepickerTittle.textColor= [UIColor yellowColor]];
isDateSearch=NO;
self.arrTitles =[[NSMutableArray alloc] init];
self.arrDescription=[[NSMutableArray alloc]init];
self.arrImages=[[NSMutableArray alloc]init];
self.arrDate=[[NSMutableArray alloc]init];
self.arrUrls=[[NSMutableArray alloc]init];
self.arrDateSearch=[[NSMutableArray alloc]init];
//[self performSelectorInBackground:#selector(requestingForNews:) withObject:nil];
// dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), s^{
self.spinnerView.hidden=YES;
[self makeRequestForNews];
// self.spinnerView.stopAnimating;
//});
// Do any additional setup after loading the view.
[self imagedownloader:#"http://www.shura.bh/MediaCenter/News/"];
self.SearchResultsArray = [[NSArray alloc] init ];
}
-(void)myindicator {
[NewsIndicator stopAnimating];
NewsIndicator.hidden =YES;
[self.tblNews reloadData];
}
-(void)requestingForNews:(id)sender
{
[self makeRequestForNews];
}
-(void) imagedownloader : (NSString *)urlStringOfImage
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
//downlaod image
NSURL *imageUrl = [NSURL URLWithString:urlStringOfImage];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50 )];
imageView.image = image;
[self.view addSubview:imageView];
});
});
}
- (void) removeUISearchBarBackgroundInViewHierarchy:(UIView *)view
{
for (UIView *subview in [view subviews]) {
if ([subview isKindOfClass:NSClassFromString(#"UISearchBarBackground")]) {
[subview removeFromSuperview];
break; //To avoid an extra loop as there is only one UISearchBarBackground
} else {
[self removeUISearchBarBackgroundInViewHierarchy:subview];
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - make request for news
-(void)makeRequestForNews
{
NSURL *url =[NSURL URLWithString:self.strNewsApi];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//After making request the apparent thing is expecting the response that may be expected response or an Error. so create those objects and intialize them with NULL.
NSURLResponse *response = NULL;
NSError *requestError =NULL;
//Once you have response with you , Capture YOur Responce data using NsData.
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
//Convert the respnse Data into Response String.
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//Now We can start parsing the Data using XMl parser . you need XML parser in-order to use the below class method "dictionaryFOrXMLString".
NSError *parserError = NULL;
//XML parsing
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:responseData];
[xmlParser setDelegate:self];
[xmlParser parse];
// NSURL *url = [NSURL URLWithString:url];
// NSData *data = [NSData dataWithContentsOfURL:url];
// UIImage *image = [UIImage imageWithData:data];
//NSDictionary *xmlDict = [XMLReader dictionaryForXMLString:responseString error:NULL];
//once you have xmlDict handy, you can pass this to the any ViewController (Like table view) to populate the Data.
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"ShuraNews"])
{
}
if ([elementName isEqualToString:#"PUBLISHINGPAGEIMAGE"])
{
}
strTemp=[NSMutableString new];
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
//temString =string;
[strTemp appendString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"TITLE"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrTitles addObject:strTemp];
}
if ([elementName isEqualToString:#"PUBLISHINGPAGECONTENT"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrDescription addObject:strTemp];
}
if ([elementName isEqualToString:#"NEWSARTICLEDATE"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrDate addObject:strTemp];
}
if ([elementName isEqualToString:#"PUBLISHINGPAGEIMAGE"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrImages addObject:strTemp];
}
if ([elementName isEqualToString:#"ShuraNews"])
{
[self.tblNews reloadData];
// self.spinnerView.hidden=YES;
}
if ([elementName isEqualToString:#"URL"])
{
[self.arrUrls addObject:strTemp];
}
}
#pragma mark - TabeView Datasource//delegate method
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView)
{
return [self.SearchResultsArray count];
}
else
{
return [self.arrTitles count];
}
if (isDateSearch)
{
return [self.arrDateSearch count];
}
else{
return [self.arrTitles count];
}
return [self.arrTitles count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView setSeparatorInset:UIEdgeInsetsZero];
static NSString *cellIdentifier=#"cellNews";
NewsTableViewCell *cell=(NewsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
// NewsTableViewCell *cell=(NewsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil)
{
cell = [[NewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
// cell.NewsTableViewCell.textColor = UIColorFromRGB(0x000000);
cell.backgroundColor=[UIColor clearColor];
}
if (tableView == self.searchDisplayController.searchResultsTableView)
{
cell.textLabel.text= [self.SearchResultsArray objectAtIndex:indexPath.row];
}
if( [indexPath row] % 2){
cell.contentView.backgroundColor =UIColorFromRGB(0Xffffff);
}
else{
cell.contentView.backgroundColor =UIColorFromRGB (0Xdcdcdc);
}
//selectbackground color start
UIView *NewsTableViewCell = [[UIView alloc] initWithFrame:cell.frame];
NewsTableViewCell.backgroundColor = UIColorFromRGB(0Xdcdcdc);
cell.selectedBackgroundView = NewsTableViewCell; //select background colro end
cell.lblTitles.font = [UIFont fontWithName:#"GEEast-ExtraBold" size:12];
if (isDateSearch)
{
cell.lblTitles.text=[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"title"];
}
else{
cell.lblTitles.text=[self.arrTitles objectAtIndex:indexPath.row];
}
cell.lblDescription.font =[UIFont fontWithName:#"GE SS Unique" size:12];
cell.lblDate.font=[UIFont fontWithName:#"GE SS Unique" size:12];
if (isDateSearch)
{
cell.lblDescription.text=[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"des"];
}
else{
cell.lblDescription.text=[self.arrDescription objectAtIndex:indexPath.row];
}
cell.lblDate.text=[self.arrDate objectAtIndex:indexPath.row];
cell.lblTitles.textAlignment= NSTextAlignmentRight;
cell.lblDate.textAlignment = NSTextAlignmentRight;
cell.lblDescription.textAlignment = NSTextAlignmentRight;
NSData *data;
if (isDateSearch)
{
data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"img"]]];
}
else{
data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]]];
}
//SDWebImage Code for lazy loader
[cell.imgNews setImageWithURL: //[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]]
[NSURL URLWithString:[[self.arrImages objectAtIndex:indexPath.row] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
// if (![self.arrImages objectAtIndex:indexPath.row])
// if ((cell.imgNews.image = image))
if (image)
{
cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
cell.imgNews.layer.borderWidth = 2.0;
cell.lblTitles.frame=CGRectMake(cell.lblTitles.frame.origin.x, cell.lblTitles.frame.origin.y, 208, cell.lblTitles.frame.size.height);
cell.lblDate.frame=CGRectMake(cell.lblDate.frame.origin.x, cell.lblDate.frame.origin.y, 208, cell.lblDate.frame.size.height);
cell.lblDescription.frame=CGRectMake(cell.lblDescription.frame.origin.x, cell.lblDescription.frame.origin.y, 206, cell.lblDescription.frame.size.height);
}
else {
// if (!cell.imgNews ==nil)
if (!cell.imgNews.image)
{
cell.lblTitles.frame=CGRectMake(cell.lblTitles.frame.origin.x, cell.lblTitles.frame.origin.y, 283, cell.lblTitles.frame.size.height);
cell.lblDate.frame=CGRectMake(cell.lblDate.frame.origin.x, cell.lblDate.frame.origin.y, 286, cell.lblDate.frame.size.height);
cell.lblDescription.frame=CGRectMake(cell.lblDescription.frame.origin.x, cell.lblDescription.frame.origin.y, 281, cell.lblDescription.frame.size.height);
cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
cell.imgNews.layer.borderWidth = 0;
}
}
}];
[PickerContainer setHidden:YES];
return cell;
}
#pragma Search Methods
-(void)filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [search] %#", searchText];
self.SearchResultsArray = [self.arrTitles filteredArrayUsingPredicate:predicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
- (void)layoutSubviews
{
if(!(searchBr == nil))
{
searchBr.frame = CGRectMake(4, 5, 185, 30);
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dict=nil;
if (isDateSearch)
{
dict=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:#"%#",[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"title"]],#"title",[NSString stringWithFormat:#"%#",[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"des"]],#"img",[NSString stringWithFormat:#"%#",[self.arrDescription objectAtIndex:indexPath.row]],#"Des",[NSString stringWithFormat:#"%#",[self.arrUrls objectAtIndex:indexPath.row]],#"url", nil];
}
else{
dict=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:#"%#",
[self.arrTitles objectAtIndex:indexPath.row]],#"title",[NSString stringWithFormat:#"%#",
[self.arrImages objectAtIndex:indexPath.row]],#"img",[NSString stringWithFormat:#"%#",
[self.arrDescription objectAtIndex:indexPath.row]],#"Des",[NSString stringWithFormat:#"%#",
[self.arrDate objectAtIndex:indexPath.row]],#"Date",[NSString stringWithFormat:#"%#",
[self.arrUrls objectAtIndex:indexPath.row]],#"url", nil];
}
[self performSegueWithIdentifier:#"NewsDetailsID" sender:dict];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"NewsDetailsID"])
{
((NewDetailsViewController *)segue.destinationViewController).strTitle=[sender objectForKey:#"title"];
((NewDetailsViewController *)segue.destinationViewController).strDetailImage=[sender objectForKey:#"img"];
((NewDetailsViewController *)segue.destinationViewController).strDescription=[sender objectForKey:#"Des"];//strUrl
((NewDetailsViewController *)segue.destinationViewController).strDate=[sender objectForKey:#"Date"];
((NewDetailsViewController *)segue.destinationViewController).strUrl=[sender objectForKey:#"url"];
}
}
- (IBAction)SearchButton:(id)sender {
if (search == 0) {
searchBr.hidden=NO;
search=1;
}
else
{
searchBr.hidden=YES;
search=0;
}
}
- (IBAction)backBtnClicked:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)DatePickerBt:(id)sender {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
PickerContainer.frame = CGRectMake(0, 150, 320, 261);
[PickerContainer setHidden:NO];
}
- (IBAction)HideButton:(id)sender
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
PickerContainer.frame = CGRectMake(0,600, 320, 261);
[UIView commitAnimations];
if ([self.arrDate count])
{
for (int i=0; i<[self.arrDate count]; i++)
{
NSArray *arrDateStr=[[self.arrDate objectAtIndex:i] componentsSeparatedByString:#" "];
// NSString *dateString=[NSString stringWithFormat:#"%# %#",[[arrDateStr objectAtIndex:0]stringByReplacingOccurrencesOfString:#"/" withString:#"-"],[arrDateStr objectAtIndex:1]];
NSString *dateString=[NSString stringWithFormat:#"%# %#",[arrDateStr objectAtIndex:0],[arrDateStr objectAtIndex:1]];
NSDateFormatter *format = [[NSDateFormatter alloc]init];
[format setDateFormat:#"dd/MM/yyyy"];
NSDate *currentDate = [format dateFromString:dateString];
if ([[[[NSString stringWithFormat:#"%#",currentDate]componentsSeparatedByString:#" "]objectAtIndex:0] isEqualToString:[[[NSString stringWithFormat:#"%#",self.datepicker.date]componentsSeparatedByString:#" "]objectAtIndex:0]])
{
isDateSearch=YES;
NSDictionary *dictTemp=[NSDictionary dictionaryWithObjectsAndKeys:[self.arrTitles objectAtIndex:i],#"title",[self.arrDescription objectAtIndex:i],#"des",[self.arrImages objectAtIndex:i],#"img", nil];
[self.arrDateSearch addObject:dictTemp];
[self.tblNews reloadData];
NSLog(#"dates equal");
}
}
}
}
- (IBAction)ReloadButton:(id)sender {
self.spinnerView.hidden=YES;
isDateSearch=NO;
[self makeRequestForNews];
NSLog(#"RELOADING!!!!!!!!!!!!!!!");
}
#end

You should definitely be using stringByAddingPercentEscapesUsingEncoding, and I do not think that this is "per se" causing the performance problem you see. That is just modifying a bit the URL you use.
I tend to think that by using stringByAddingPercentEscapesUsingEncoding your app is getting all of the images (as opposed to just a few of them) and this is making it slower.
E.g., if the images you download are large, then this might explain the app slowness, both in terms of how long you have to wait for the image to be available and to scale it down to cell size.
EDIT:
I checked the site http://www.shura.bh/MediaCenter/News and images are indeed large. They take quite a while to download in Safari. I have found images as large as 4000x3000px, and this is definitely too large.

Related

XML image Loading issue in Xcode?

In my application news displaying through XML parser , The problem is In my XMl url few images are named with Arabic language those images are loading , If its named with English (Ex.dsc_5804.jpg) its displaying fine and if its named with Arabic (Ex.لجنة%20تطوير%20الإعلام%20في%20الشورى%20تبدأ%20ف.jpg) its not displaying , i am not sure the issue with image format or from my code or something else can any tel me the solution for this please ??
YOU CAN SEE MY SCREEN SHOT ALSO CLICK HERE
Image url link here
Here is my NewsViewController.m
#import "NewsViewController.h"
#import "NewsTableViewCell.h"
#import "NewDetailsViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "SearchVC.h"
#interface NewsViewController ()
{
NSString *temString;
NSMutableString *strTemp;
BOOL isDateSearch;
}
#end
#implementation NewsViewController
#synthesize arrImages;
#synthesize TittleOne;
#synthesize TittleTwo;
#synthesize TittleThree;
#synthesize datepicker;
#synthesize PickerContainer;
#synthesize datepickerTittle;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
#pragma mark - View Life Cycle
- (void)viewDidLoad
{
UIActivityIndicatorView *spinnerView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[super viewDidLoad];
[TittleOne setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
[TittleTwo setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:10]];
[TittleThree setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:10]];
// [[UIColor redColor] set];
[datepickerTittle setFont:[UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
// [datepickerTittle.textColor= [UIColor yellowColor]];
isDateSearch=NO;
self.arrTitles =[[NSMutableArray alloc] init];
self.arrDescription=[[NSMutableArray alloc]init];
self.arrImages=[[NSMutableArray alloc]init];
self.arrDate=[[NSMutableArray alloc]init];
self.arrUrls=[[NSMutableArray alloc]init];
self.arrDateSearch=[[NSMutableArray alloc]init];
//[self performSelectorInBackground:#selector(requestingForNews:) withObject:nil];
// dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), s^{
self.spinnerView.hidden=YES;
[self makeRequestForNews];
// self.spinnerView.stopAnimating;
//});
// Do any additional setup after loading the view.
[self imagedownloader:#"http://www.shura.bh/MediaCenter/News/"];
}
-(void)requestingForNews:(id)sender
{
[self makeRequestForNews];
}
-(void) imagedownloader : (NSString *)urlStringOfImage
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
//downlaod image
NSURL *imageUrl = [NSURL URLWithString:urlStringOfImage];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50 )];
imageView.image = image;
[self.view addSubview:imageView];
});
});
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - make request for news
-(void)makeRequestForNews
{
NSURL *url =[NSURL URLWithString:self.strNewsApi];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//After making request the apparent thing is expecting the response that may be expected response or an Error. so create those objects and intialize them with NULL.
NSURLResponse *response = NULL;
NSError *requestError =NULL;
//Once you have response with you , Capture YOur Responce data using NsData.
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
//Convert the respnse Data into Response String.
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//Now We can start parsing the Data using XMl parser . you need XML parser in-order to use the below class method "dictionaryFOrXMLString".
NSError *parserError = NULL;
//XML parsing
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:responseData];
[xmlParser setDelegate:self];
[xmlParser parse];
// NSURL *url = [NSURL URLWithString:url];
// NSData *data = [NSData dataWithContentsOfURL:url];
// UIImage *image = [UIImage imageWithData:data];
//NSDictionary *xmlDict = [XMLReader dictionaryForXMLString:responseString error:NULL];
//once you have xmlDict handy, you can pass this to the any ViewController (Like table view) to populate the Data.
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"ShuraNews"])
{
}
if ([elementName isEqualToString:#"PUBLISHINGPAGEIMAGE"])
{
}
strTemp=[NSMutableString new];
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
//temString =string;
[strTemp appendString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"TITLE"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrTitles addObject:strTemp];
}
if ([elementName isEqualToString:#"PUBLISHINGPAGECONTENT"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrDescription addObject:strTemp];
}
if ([elementName isEqualToString:#"NEWSARTICLEDATE"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrDate addObject:strTemp];
}
if ([elementName isEqualToString:#"PUBLISHINGPAGEIMAGE"])
{
NSLog(#"tempImage=== %#", strTemp);
[self.arrImages addObject:strTemp];
}
if ([elementName isEqualToString:#"ShuraNews"])
{
[self.tblNews reloadData];
// self.spinnerView.hidden=YES;
}
if ([elementName isEqualToString:#"URL"])
{
[self.arrUrls addObject:strTemp];
}
}
#pragma mark - TabeView Datasource//delegate method
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (isDateSearch)
{
return [self.arrDateSearch count];
}
else{
return [self.arrTitles count];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView setSeparatorInset:UIEdgeInsetsZero];
static NSString *cellIdentifier=#"cellNews";
NewsTableViewCell *cell=(NewsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil)
{
cell = [[NewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
// cell.NewsTableViewCell.textColor = UIColorFromRGB(0x000000);
cell.backgroundColor=[UIColor clearColor];
}
if( [indexPath row] % 2){
cell.contentView.backgroundColor =UIColorFromRGB(0Xffffff);
}
else{
cell.contentView.backgroundColor =UIColorFromRGB (0Xdcdcdc);
}
//selectbackground color start
UIView *NewsTableViewCell = [[UIView alloc] initWithFrame:cell.frame];
NewsTableViewCell.backgroundColor = UIColorFromRGB(0Xdcdcdc);
cell.selectedBackgroundView = NewsTableViewCell; //select background colro end
cell.lblTitles.font = [UIFont fontWithName:#"GEEast-ExtraBold" size:12];
if (isDateSearch)
{
cell.lblTitles.text=[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"title"];
}
else{
cell.lblTitles.text=[self.arrTitles objectAtIndex:indexPath.row];
}
cell.lblDescription.font =[UIFont fontWithName:#"GE SS Unique" size:12];
cell.lblDate.font=[UIFont fontWithName:#"GE SS Unique" size:12];
if (isDateSearch)
{
cell.lblDescription.text=[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"des"];
}
else{
cell.lblDescription.text=[self.arrDescription objectAtIndex:indexPath.row];
}
cell.lblDate.text=[self.arrDate objectAtIndex:indexPath.row];
cell.lblTitles.textAlignment= NSTextAlignmentRight;
cell.lblDate.textAlignment = NSTextAlignmentRight;
cell.lblDescription.textAlignment = NSTextAlignmentRight;
//SDWebImage Code for lazy loader
[cell.imgNews setImageWithURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
// if (![self.arrImages objectAtIndex:indexPath.row])
if ((cell.imgNews.image = image))
{
cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
cell.imgNews.layer.borderWidth = 2.0;
}
else {
// if (!cell.imgNews ==nil)
if (!cell.imgNews.image)
{
cell.lblTitles.frame=CGRectMake(cell.lblTitles.frame.origin.x, cell.lblTitles.frame.origin.y, 283, cell.lblTitles.frame.size.height);
cell.lblDate.frame=CGRectMake(cell.lblDate.frame.origin.x, cell.lblDate.frame.origin.y, 286, cell.lblDate.frame.size.height);
cell.lblDescription.frame=CGRectMake(cell.lblDescription.frame.origin.x, cell.lblDescription.frame.origin.y, 281, cell.lblDescription.frame.size.height);
cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
cell.imgNews.layer.borderWidth = 0;
}
}
}];
// cell.imgNews.image=[UIImage imageWithData:data];
// cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
// cell.imgNews.layer.borderWidth = 2.0;
[PickerContainer setHidden:YES];
// if (!cell.imgNews.image)
// {
// cell.lblTitles.frame=CGRectMake(cell.lblTitles.frame.origin.x, cell.lblTitles.frame.origin.y, 283, cell.lblTitles.frame.size.height);
// cell.lblDate.frame=CGRectMake(cell.lblDate.frame.origin.x, cell.lblDate.frame.origin.y, 286, cell.lblDate.frame.size.height);
// cell.lblDescription.frame=CGRectMake(cell.lblDescription.frame.origin.x, cell.lblDescription.frame.origin.y, 281, cell.lblDescription.frame.size.height);
// cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
// cell.imgNews.layer.borderWidth = 0;
// }
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dict=nil;
if (isDateSearch)
{
//dict=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:#"%#",[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"title"]],#"title",[NSString stringWithFormat:#"%#",[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"des"]],#"img",[NSString stringWithFormat:#"%#",[self.arrDescription objectAtIndex:indexPath.row]],#"Des",[NSString stringWithFormat:#"%#",[self.arrUrls objectAtIndex:indexPath.row]],#"url", nil];
}
else{
dict=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:#"%#",
[self.arrTitles objectAtIndex:indexPath.row]],#"title",[NSString stringWithFormat:#"%#",
[self.arrImages objectAtIndex:indexPath.row]],#"img",[NSString stringWithFormat:#"%#",
[self.arrDescription objectAtIndex:indexPath.row]],#"Des",[NSString stringWithFormat:#"%#",[self.arrUrls objectAtIndex:indexPath.row]],#"url", nil];
}
[self performSegueWithIdentifier:#"NewsDetailsID" sender:dict];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"NewsDetailsID"])
{
((NewDetailsViewController *)segue.destinationViewController).strTitle=[sender objectForKey:#"title"];
((NewDetailsViewController *)segue.destinationViewController).strDetailImage=[sender objectForKey:#"img"];
((NewDetailsViewController *)segue.destinationViewController).strDescription=[sender objectForKey:#"Des"];//strUrl
((NewDetailsViewController *)segue.destinationViewController).strUrl=[sender objectForKey:#"url"];
}
}
- (IBAction)backBtnClicked:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)DatePickerBt:(id)sender {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
PickerContainer.frame = CGRectMake(0, 150, 320, 261);
[PickerContainer setHidden:NO];
}
- (IBAction)HideButton:(id)sender
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
PickerContainer.frame = CGRectMake(0,600, 320, 261);
[UIView commitAnimations];
if ([self.arrDateSearch count])
{
[self.arrDateSearch removeAllObjects];
}
if ([self.arrDate count])
{
for (int i=0; i<[self.arrDate count]; i++)
{
NSLog(#"arrdate === %#",self.arrDate);
NSArray *arrDateStr=[[self.arrDate objectAtIndex:i] componentsSeparatedByString:#" "];
NSArray *arrDat=[[NSString stringWithFormat:#"%#",[arrDateStr objectAtIndex:0]] componentsSeparatedByString:#"/"];
NSString *strDat=[NSString stringWithFormat:#"%#-%#-%#",[arrDat objectAtIndex:2],[arrDat objectAtIndex:1],[arrDat objectAtIndex:0]];
NSString *strPicDat=[[[NSString stringWithFormat:#"%#",self.datepicker.date]componentsSeparatedByString:#" "]objectAtIndex:0];
NSLog(#" strpic date === %#",strPicDat);
if ([strDat isEqualToString:strPicDat])
{
isDateSearch=YES;
NSDictionary *dictTemp=[NSDictionary dictionaryWithObjectsAndKeys:[self.arrTitles objectAtIndex:i],#"title",[self.arrDescription objectAtIndex:i],#"des",[self.arrImages objectAtIndex:i],#"img", nil];
[self.arrDateSearch addObject:dictTemp];
NSLog(#"dates equal");
}
}
[self.tblNews reloadData];
}
}
- (IBAction)ReloadButton:(id)sender {
self.spinnerView.hidden=NO;
isDateSearch=NO;
[self makeRequestForNews];
NSLog(#"RELOADING!!!!!!!!!!!!!!!");
}
#end
Can you try the following code
-(void) imagedownloader : (NSString *)urlStringOfImage
{
urlStringOfImage = [urlStringOfImage stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
//OR
urlStringOfImage = [urlStringOfImage stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// DO YOUR NORMAL STUFF YOU WERE DOING.
}
Update
I think in your case the other method that is stringByReplacingPercent rather than stringByAddingPercent should work, try following
urlStringOfImage = [urlStringOfImage stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Update2
The url you gave is not a valid url see image, I think you should report to the webservice developer to put valid url encoding, or better change your webservice for image urls, with use of uniqueID or, something.

UILabels are Hidding behind the Image View cell?

Hi I have issue with Labels ,i.e , I have a XML NewsViewController where i am displaying the News . You can see the Screen shot (NewsViewController.jpg) In NewsViewController i am displaying the Tittle, Date and Description labels , those labels are hiding behind the imageView cell But in the Few News List are displaying fine .Can any one Help me ??
Below i have given the NewsViewController code please check
Here is my NewsViewController.m
#import "NewsViewController.h"
#import "NewsTableViewCell.h"
#import "NewDetailsViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#interface NewsViewController ()
{
NSString *temString;
NSMutableString *strTemp;
BOOL isDateSearch;
}
#end
#implementation NewsViewController
#synthesize arrImages;
#synthesize TittleOne;
#synthesize TittleTwo;
#synthesize TittleThree;
#synthesize datepicker;
#synthesize PickerContainer;
#synthesize datepickerTittle;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
#pragma mark - View Life Cycle
- (void)viewDidLoad
{
[super viewDidLoad];
[TittleOne setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
[TittleTwo setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:10]];
[TittleThree setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:10]];
// [[UIColor redColor] set];
[datepickerTittle setFont:[UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
// [datepickerTittle.textColor= [UIColor yellowColor]];
isDateSearch=NO;
self.arrTitles =[[NSMutableArray alloc] init];
self.arrDescription=[[NSMutableArray alloc]init];
self.arrImages=[[NSMutableArray alloc]init];
self.arrDate=[[NSMutableArray alloc]init];
self.arrUrls=[[NSMutableArray alloc]init];
self.arrDateSearch=[[NSMutableArray alloc]init];
//[self performSelectorInBackground:#selector(requestingForNews:) withObject:nil];
// dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), s^{
self.spinnerView.hidden=YES;
[self makeRequestForNews];
// self.spinnerView.stopAnimating;
//});
// Do any additional setup after loading the view.
[self imagedownloader:#"http://www.shura.bh/MediaCenter/News/"];
}
-(void)requestingForNews:(id)sender
{
[self makeRequestForNews];
}
-(void) imagedownloader : (NSString *)urlStringOfImage
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
//downlaod image
NSURL *imageUrl = [NSURL URLWithString:urlStringOfImage];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50 )];
imageView.image = image;
[self.view addSubview:imageView];
});
});
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - make request for news
-(void)makeRequestForNews
{
NSURL *url =[NSURL URLWithString:self.strNewsApi];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//After making request the apparent thing is expecting the response that may be expected response or an Error. so create those objects and intialize them with NULL.
NSURLResponse *response = NULL;
NSError *requestError =NULL;
//Once you have response with you , Capture YOur Responce data using NsData.
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
//Convert the respnse Data into Response String.
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//Now We can start parsing the Data using XMl parser . you need XML parser in-order to use the below class method "dictionaryFOrXMLString".
NSError *parserError = NULL;
//XML parsing
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:responseData];
[xmlParser setDelegate:self];
[xmlParser parse];
// NSURL *url = [NSURL URLWithString:url];
// NSData *data = [NSData dataWithContentsOfURL:url];
// UIImage *image = [UIImage imageWithData:data];
//NSDictionary *xmlDict = [XMLReader dictionaryForXMLString:responseString error:NULL];
//once you have xmlDict handy, you can pass this to the any ViewController (Like table view) to populate the Data.
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"ShuraNews"])
{
}
if ([elementName isEqualToString:#"PUBLISHINGPAGEIMAGE"])
{
}
strTemp=[NSMutableString new];
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
//temString =string;
[strTemp appendString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"TITLE"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrTitles addObject:strTemp];
}
if ([elementName isEqualToString:#"PUBLISHINGPAGECONTENT"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrDescription addObject:strTemp];
}
if ([elementName isEqualToString:#"NEWSARTICLEDATE"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrDate addObject:strTemp];
}
if ([elementName isEqualToString:#"PUBLISHINGPAGEIMAGE"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrImages addObject:strTemp];
}
if ([elementName isEqualToString:#"ShuraNews"])
{
[self.tblNews reloadData];
// self.spinnerView.hidden=YES;
}
if ([elementName isEqualToString:#"URL"])
{
[self.arrUrls addObject:strTemp];
}
}
#pragma mark - TabeView Datasource//delegate method
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (isDateSearch)
{
return [self.arrDateSearch count];
}
else{
return [self.arrTitles count];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView setSeparatorInset:UIEdgeInsetsZero];
static NSString *cellIdentifier=#"cellNews";
NewsTableViewCell *cell=(NewsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil)
{
cell = [[NewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
// cell.NewsTableViewCell.textColor = UIColorFromRGB(0x000000);
cell.backgroundColor=[UIColor clearColor];
}
if( [indexPath row] % 2){
cell.contentView.backgroundColor =UIColorFromRGB(0Xffffff);
}
else{
cell.contentView.backgroundColor =UIColorFromRGB (0Xdcdcdc);
}
//selectbackground color start
UIView *NewsTableViewCell = [[UIView alloc] initWithFrame:cell.frame];
NewsTableViewCell.backgroundColor = UIColorFromRGB(0Xdcdcdc);
cell.selectedBackgroundView = NewsTableViewCell; //select background colro end
cell.lblTitles.font = [UIFont fontWithName:#"GEEast-ExtraBold" size:12];
if (isDateSearch)
{
cell.lblTitles.text=[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"title"];
}
else{
cell.lblTitles.text=[self.arrTitles objectAtIndex:indexPath.row];
}
cell.lblDescription.font =[UIFont fontWithName:#"GE SS Unique" size:12];
cell.lblDate.font=[UIFont fontWithName:#"GE SS Unique" size:12];
if (isDateSearch)
{
cell.lblDescription.text=[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"des"];
}
else{
cell.lblDescription.text=[self.arrDescription objectAtIndex:indexPath.row];
}
cell.lblDate.text=[self.arrDate objectAtIndex:indexPath.row];
cell.lblTitles.textAlignment= NSTextAlignmentRight;
cell.lblDate.textAlignment = NSTextAlignmentRight;
cell.lblDescription.textAlignment = NSTextAlignmentRight;
//SDWebImage Code for lazy loader
[cell.imgNews setImageWithURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:#""]];
// cell.imgNews.image=[UIImage imageWithData:data];
cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
cell.imgNews.layer.borderWidth = 2.0;
[PickerContainer setHidden:YES];
if (!cell.imgNews.image)
{
cell.lblTitles.frame=CGRectMake(cell.lblTitles.frame.origin.x, cell.lblTitles.frame.origin.y, 283, cell.lblTitles.frame.size.height);
cell.lblDate.frame=CGRectMake(cell.lblDate.frame.origin.x, cell.lblDate.frame.origin.y, 286, cell.lblDate.frame.size.height);
cell.lblDescription.frame=CGRectMake(cell.lblDescription.frame.origin.x, cell.lblDescription.frame.origin.y, 281, cell.lblDescription.frame.size.height);
cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
cell.imgNews.layer.borderWidth = 0;
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dict=nil;
if (isDateSearch)
{
//dict=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:#"%#",[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"title"]],#"title",[NSString stringWithFormat:#"%#",[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"des"]],#"img",[NSString stringWithFormat:#"%#",[self.arrDescription objectAtIndex:indexPath.row]],#"Des",[NSString stringWithFormat:#"%#",[self.arrUrls objectAtIndex:indexPath.row]],#"url", nil];
}
else{
dict=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:#"%#",
[self.arrTitles objectAtIndex:indexPath.row]],#"title",[NSString stringWithFormat:#"%#",
[self.arrImages objectAtIndex:indexPath.row]],#"img",[NSString stringWithFormat:#"%#",
[self.arrDescription objectAtIndex:indexPath.row]],#"Des",[NSString stringWithFormat:#"%#",[self.arrUrls objectAtIndex:indexPath.row]],#"url", nil];
}
[self performSegueWithIdentifier:#"NewsDetailsID" sender:dict];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"NewsDetailsID"])
{
((NewDetailsViewController *)segue.destinationViewController).strTitle=[sender objectForKey:#"title"];
((NewDetailsViewController *)segue.destinationViewController).strDetailImage=[sender objectForKey:#"img"];
((NewDetailsViewController *)segue.destinationViewController).strDescription=[sender objectForKey:#"Des"];//strUrl
((NewDetailsViewController *)segue.destinationViewController).strUrl=[sender objectForKey:#"url"];
}
}
- (IBAction)backBtnClicked:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)DatePickerBt:(id)sender {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
PickerContainer.frame = CGRectMake(0, 150, 320, 261);
[PickerContainer setHidden:NO];
}
- (IBAction)HideButton:(id)sender
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
PickerContainer.frame = CGRectMake(0,600, 320, 261);
[UIView commitAnimations];
if ([self.arrDateSearch count])
{
[self.arrDateSearch removeAllObjects];
}
if ([self.arrDate count])
{
for (int i=0; i<[self.arrDate count]; i++)
{
NSLog(#"arrdate === %#",self.arrDate);
NSArray *arrDateStr=[[self.arrDate objectAtIndex:i] componentsSeparatedByString:#" "];
NSArray *arrDat=[[NSString stringWithFormat:#"%#",[arrDateStr objectAtIndex:0]] componentsSeparatedByString:#"/"];
NSString *strDat=[NSString stringWithFormat:#"%#-%#-%#",[arrDat objectAtIndex:2],[arrDat objectAtIndex:1],[arrDat objectAtIndex:0]];
NSString *strPicDat=[[[NSString stringWithFormat:#"%#",self.datepicker.date]componentsSeparatedByString:#" "]objectAtIndex:0];
NSLog(#" strpic date === %#",strPicDat);
if ([strDat isEqualToString:strPicDat])
{
isDateSearch=YES;
NSDictionary *dictTemp=[NSDictionary dictionaryWithObjectsAndKeys:[self.arrTitles objectAtIndex:i],#"title",[self.arrDescription objectAtIndex:i],#"des",[self.arrImages objectAtIndex:i],#"img", nil];
[self.arrDateSearch addObject:dictTemp];
NSLog(#"dates equal");
}
}
[self.tblNews reloadData];
}
}
- (IBAction)ReloadButton:(id)sender {
}
#end
Below i have given the Screen shots
NewsViewController Link Here
DetailsViewController Link here
There are two questions here. Ill answer the one about the tableview.
The SDWebImage category on UIImageView (UIImageView+WebCache) is an async API , hence when you work out whether there is an image there and arrange your text frame it always evaluates to NO
[cell.imgNews setImageWithURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:#""]];
...
if (!cell.imgNews.image)
{
//setup text frame
}
what you are calling is a convenience method for this...
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock;
so try this...
[cell.imgNews setImageWithURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]]
placeholderImage:[UIImage imageNamed:#""]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
...
if (image) {
//setup text frame for image
}
else {
//setup text for no image as cell is recycled and may have held image previously
}
}];
Please view your InterfaceBuilder Screenshots 2 and 3.
The Large image (3) has the autoresizing mask set so that the margin to the right is maintained. #
It looks like this
_ | _
The Label besides the small image in the UITableViewCell however only mainains the margins to the top and the left. Set to keep it on the right as well and it won't overflow anymore.
Make it look like the mask above.
Of course you'd have to do this for all 3 labels. Alternatvively you could wrap the 3 labels in a view and only do the autoresizing mask stuff for this container and make the labels fill out the entire width of the container.
I will answer the question regarding the cells in "NewsViewController".
Using [UIImage imageNamed:#""] is equivalent to passing nil. UIImage class will not find an image with a name of empty string, so it will return nil.
When you check cell.imgNews's image, it will be nil as the real image is still not loaded yet.
You have two options:
1- Use a placeholder image.
2- Check for the image url instead of the image itself. like if (![self.arrImages objectAtIndex:indexPath.row]).
Note: Make sure the data arrays have the same length. If one of them has different length, you will get out of bounds exception. One way of solving this is using a custom class that hold all related information. Then build an array of it.

How To Search The TableviewData in Different ViewController?

I have a NewsViewController where News Displaying Form XML , My Problem is I Created Separate Class Called SearchVC and I have Added the Search Bar, Here I want search the all the News
(from NewsViewController). The Search Result Should Display in the Drop down List, If i click those Search result It should Redirect to the NewsDetailsViewController. I do not know how to do this can any one help me out of this issue .
Here is my NewsViewController.m
#import "NewsViewController.h"
#import "NewsTableViewCell.h"
#import "NewDetailsViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#interface NewsViewController ()
{
NSString *temString;
NSMutableString *strTemp;
}
#end
#implementation NewsViewController
#synthesize arrImages;
#synthesize TittleOne;
#synthesize TittleTwo;
#synthesize TittleThree;
#synthesize datepicker;
#synthesize PickerContainer;
#synthesize datepickerTittle;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
#pragma mark - View Life Cycle
- (void)viewDidLoad
{
[TittleOne setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
[TittleTwo setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:10]];
[TittleThree setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:10]];
// [[UIColor redColor] set];
[datepickerTittle setFont:[UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
// [datepickerTittle.textColor= [UIColor yellowColor]];
[super viewDidLoad];
self.arrTitles =[[NSMutableArray alloc] init];
self.arrDescription=[[NSMutableArray alloc]init];
self.arrImages=[[NSMutableArray alloc]init];
self.arrDate=[[NSMutableArray alloc]init];
self.arrUrls=[[NSMutableArray alloc]init];
//[self performSelectorInBackground:#selector(requestingForNews:) withObject:nil];
// dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), s^{
self.spinnerView.hidden=NO;
[self makeRequestForNews];
// self.spinnerView.stopAnimating;
//});
// Do any additional setup after loading the view.
[self imagedownloader:#"http://www.shura.bh/MediaCenter/News/"];
}
-(void)requestingForNews:(id)sender
{
[self makeRequestForNews];
}
-(void) imagedownloader : (NSString *)urlStringOfImage
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
//downlaod image
NSURL *imageUrl = [NSURL URLWithString:urlStringOfImage];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50 )];
imageView.image = image;
[self.view addSubview:imageView];
});
});
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - make request for news
-(void)makeRequestForNews
{
NSURL *url =[NSURL URLWithString:self.strNewsApi];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//After making request the apparent thing is expecting the response that may be expected response or an Error. so create those objects and intialize them with NULL.
NSURLResponse *response = NULL;
NSError *requestError =NULL;
//Once you have response with you , Capture YOur Responce data using NsData.
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
//Convert the respnse Data into Response String.
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//Now We can start parsing the Data using XMl parser . you need XML parser in-order to use the below class method "dictionaryFOrXMLString".
NSError *parserError = NULL;
//XML parsing
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:responseData];
[xmlParser setDelegate:self];
[xmlParser parse];
// NSURL *url = [NSURL URLWithString:url];
// NSData *data = [NSData dataWithContentsOfURL:url];
// UIImage *image = [UIImage imageWithData:data];
//NSDictionary *xmlDict = [XMLReader dictionaryForXMLString:responseString error:NULL];
//once you have xmlDict handy, you can pass this to the any ViewController (Like table view) to populate the Data.
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"ShuraNews"])
{
}
if ([elementName isEqualToString:#"PUBLISHINGPAGEIMAGE"])
{
}
strTemp=[NSMutableString new];
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
//temString =string;
[strTemp appendString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"TITLE"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrTitles addObject:strTemp];
}
if ([elementName isEqualToString:#"PUBLISHINGPAGECONTENT"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrDescription addObject:strTemp];
}
if ([elementName isEqualToString:#"NEWSARTICLEDATE"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrDate addObject:strTemp];
}
if ([elementName isEqualToString:#"PUBLISHINGPAGEIMAGE"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrImages addObject:strTemp];
}
if ([elementName isEqualToString:#"ShuraNews"])
{
[self.tblNews reloadData];
// self.spinnerView.hidden=YES;
}
if ([elementName isEqualToString:#"URL"])
{
[self.arrUrls addObject:strTemp];
}
}
#pragma mark - TabeView Datasource//delegate method
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.arrTitles count];
//
// NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
// [dateFormatter setTimeStyle:NSDateFormatterFullStyle];
// [dateFormatter setDateFormat:#"dd mmm yyyy"];
// [datepicker sortUsingComparator:^(id dateObje1,id dateObje2)
// {
// NSDate *date1 = [dateFormatter dateFromString:[(datepicker) dateObje1 arrDate]];
// NSDate *date2 = [dateFormatter dateFromString:[(datepicker) dateObje2 arrDate]];
// return [date2 compare:date1];
// }
// ];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView setSeparatorInset:UIEdgeInsetsZero];
static NSString *cellIdentifier=#"cellNews";
NewsTableViewCell *cell=(NewsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil)
{
cell = [[NewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
// cell.NewsTableViewCell.textColor = UIColorFromRGB(0x000000);
cell.backgroundColor=[UIColor clearColor];
//SDWebImage Code for lazy loader
[cell.imgNews setImageWithURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:#"placeholder.gif"]];
}
if( [indexPath row] % 2){
cell.contentView.backgroundColor =UIColorFromRGB(0Xffffff);
}
else{
cell.contentView.backgroundColor =UIColorFromRGB (0Xdcdcdc);
}
//selectbackground color start
UIView *NewsTableViewCell = [[UIView alloc] initWithFrame:cell.frame];
NewsTableViewCell.backgroundColor = UIColorFromRGB(0Xdcdcdc);
cell.selectedBackgroundView = NewsTableViewCell; //select background colro end
cell.lblTitles.font = [UIFont fontWithName:#"GEEast-ExtraBold" size:12];
cell.lblTitles.text=[self.arrTitles objectAtIndex:indexPath.row];
cell.lblDescription.font =[UIFont fontWithName:#"GE SS Unique" size:12];
cell.lblDate.font=[UIFont fontWithName:#"GE SS Unique" size:12];
cell.lblDescription.text=[self.arrDescription objectAtIndex:indexPath.row];
cell.lblDate.text=[self.arrDate objectAtIndex:indexPath.row];
cell.lblTitles.textAlignment= NSTextAlignmentRight;
cell.lblDate.textAlignment = NSTextAlignmentRight;
cell.lblDescription.textAlignment = NSTextAlignmentRight;
//cell.imageView.image = [UIImage imageNamed:[arrImages objectAtIndex:indexPath.row]];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]]];
cell.imgNews.image=[UIImage imageWithData:data];
cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
cell.imgNews.layer.borderWidth = 2.0;
[PickerContainer setHidden:YES];
if (!cell.imgNews.image)
{
cell.lblTitles.frame=CGRectMake(cell.lblTitles.frame.origin.x, cell.lblTitles.frame.origin.y, 283, cell.lblTitles.frame.size.height);
cell.lblDate.frame=CGRectMake(cell.lblDate.frame.origin.x, cell.lblDate.frame.origin.y, 286, cell.lblDate.frame.size.height);
cell.lblDescription.frame=CGRectMake(cell.lblDescription.frame.origin.x, cell.lblDescription.frame.origin.y, 281, cell.lblDescription.frame.size.height);
cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
cell.imgNews.layer.borderWidth = 0;
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dict=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:#"%#",
[self.arrTitles objectAtIndex:indexPath.row]],#"title",[NSString stringWithFormat:#"%#",
[self.arrImages objectAtIndex:indexPath.row]],#"img",[NSString stringWithFormat:#"%#",
[self.arrDescription objectAtIndex:indexPath.row]],#"Des",[NSString stringWithFormat:#"%#",[self.arrUrls objectAtIndex:indexPath.row]],#"url", nil];
[self performSegueWithIdentifier:#"NewsDetailsID" sender:dict];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"NewsDetailsID"])
{
((NewDetailsViewController *)segue.destinationViewController).strTitle=[sender objectForKey:#"title"];
((NewDetailsViewController *)segue.destinationViewController).strDetailImage=[sender objectForKey:#"img"];
((NewDetailsViewController *)segue.destinationViewController).strDescription=[sender objectForKey:#"Des"];//strUrl
((NewDetailsViewController *)segue.destinationViewController).strUrl=[sender objectForKey:#"url"];
}
}
- (IBAction)backBtnClicked:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
#end
Thanks In Advance.
As far as searching is concerned, You'll have to search your arrays in the NewsViewController, based on keywords that the user enters and if any results are returned, the perform a segue to your NewsDetailsViewController where those results will be displayed. For performing segue to the NewsDetailsViewController, you can use this method,
[self performSegueWithIdentifier:#"segueIdentifier" sender:nil];
Another suggestion is to use UITableViewController instead of Dropdown. The reason being that it is available in the SDK itself and you can show somewhat more data using TableView whereas Dropdown has to be made custom.

UITableview Delegate methods are not executing

i tried the following code for searching in epub ,Its not working the reason is
1.The table delegate methode executing at startup so the default value of search results is 0 ,so i give one dummy array with 4 elements in viewdidload method.So now tableview displaying only 4 thode elements in dummy array and when i scroll the tableview it displaying correct search results but still it showing only 4 elemets in that search results because number of rows methode is not execute while scrolling.
when i click search button it will call this methode in first class
SearchResultsViewController *searchRes=[[SearchResultsViewController alloc]initWithNibName:#"SearchResultsViewController" bundle:nil];
NSString *searchQuery=[search text];
sharedManager=[Mymanager sharedManager];
sharedManager.searchQuery=searchQuery;
// UITextField *textField = [NSString stringWithFormat:#"%#",searchQuery];
// [textField setFont:[UIFont fontWithName:#"BL-Ruthika-Bold" size:15]];
[searchRes searchString:searchQuery];
[self.navigationController pushViewController:searchRes animated:YES];
then it calls following methods in searchresult class
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSLog(#"%d",[results count]);
if([results count]>0)
{
return [results count];
}
else
{
return [test count];
}
}
//executes only at the startup time ,so the value of results always become zero
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
if([results count]>0) {
// cell.textLabel.adjustsFontSizeToFitWidth = YES;
hit = (SearchResult*)[results objectAtIndex:[indexPath row]];
cell.textLabel.text = [NSString stringWithFormat:#"...%#...", hit.neighboringText];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Chapter %d - page %d", hit.chapterIndex, hit.pageIndex+1];
cell.textLabel.font = [UIFont fontWithName:#"Trebuchet MS" size:13];
cell.textLabel.textColor = [UIColor colorWithRed:25/255.0 green:90/255.0 blue:100/255.0 alpha:1];
cell.detailTextLabel.textColor=[UIColor colorWithRed:25/255.0 green:90/255.0 blue:100/255.0 alpha:1];
cell.detailTextLabel.font= [UIFont fontWithName:#"Trebuchet MS" size:10];
return cell;
}
else
{
cell.textLabel.text=[test objectAtIndex:indexPath.row];
return cell;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
sharedManager=[Mymanager sharedManager];
hit = (SearchResult*)[results objectAtIndex:[indexPath row]];
sharedManager.searchFlag=YES;
sharedManager.hitPageNumber=hit.pageIndex;
sharedManager.hitChapter=hit.chapterIndex;
sharedManager.hit=hit;
// [fvc loadSpine:hit.chapterIndex atPageIndex:hit.pageIndex highlightSearchResult:hit];
[self.navigationController popViewControllerAnimated:YES];
}
- (void) searchString:(NSString*)query{
currentQuery=sharedManager.searchQuery;
[self searchString:currentQuery inChapterAtIndex:0];
[[self resultsTableView]reloadData];
}
- (void) searchString:(NSString *)query inChapterAtIndex:(int)index{
currentChapterIndex = index;
sharedManager=[Mymanager sharedManager];
Chapter* chapter = [sharedManager.spineArray objectAtIndex:index];
NSRange range = NSMakeRange(0, chapter.text.length);
NSLog(#"%#",sharedManager.searchQuery);
range = [chapter.text rangeOfString:sharedManager.searchQuery options:NSCaseInsensitiveSearch range:range locale:nil];
int hitCount=0;
while (range.location != NSNotFound) {
range = NSMakeRange(range.location+range.length, chapter.text.length-(range.location+range.length));
range = [chapter.text rangeOfString:sharedManager.searchQuery options:NSCaseInsensitiveSearch range:range locale:nil];
hitCount++;
}
if(hitCount!=0){
UIWebView* webView = [[UIWebView alloc] initWithFrame:chapter.windowSize];
[webView setDelegate:self];
NSURLRequest* urlRequest = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:chapter.spinePath]];
[webView loadRequest:urlRequest];
} else {
if((currentChapterIndex+1)<[sharedManager.spineArray count]){
[self searchString:sharedManager.searchQuery inChapterAtIndex:(currentChapterIndex+1)];
} else {
fvc.searching = NO;
}
}
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
// NSLog(#"%#", error);
[webView release];
}
- (void) webViewDidFinishLoad:(UIWebView*)webView{
sharedManager=[Mymanager sharedManager];
NSString *varMySheet = #"var mySheet = document.styleSheets[0];";
NSString *addCSSRule = #"function addCSSRule(selector, newRule) {"
"if (mySheet.addRule) {"
"mySheet.addRule(selector, newRule);" // For Internet Explorer
"} else {"
"ruleIndex = mySheet.cssRules.length;"
"mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex);" // For Firefox, Chrome, etc.
"}"
"}";
NSString *insertRule1 = [NSString stringWithFormat:#"addCSSRule('html', 'padding: 0px; height: %fpx; -webkit-column-gap: 0px; -webkit-column-width: %fpx;')", webView.frame.size.height, webView.frame.size.width];
NSString *insertRule2 = [NSString stringWithFormat:#"addCSSRule('p', 'text-align: justify;')"];
NSString *setTextSizeRule = [NSString stringWithFormat:#"addCSSRule('body', '-webkit-text-size-adjust: %d%%;')",[[sharedManager.spineArray objectAtIndex:currentChapterIndex] fontPercentSize]];
[webView stringByEvaluatingJavaScriptFromString:varMySheet];
[webView stringByEvaluatingJavaScriptFromString:addCSSRule];
[webView stringByEvaluatingJavaScriptFromString:insertRule1];
[webView stringByEvaluatingJavaScriptFromString:insertRule2];
[webView stringByEvaluatingJavaScriptFromString:setTextSizeRule];
[webView highlightAllOccurencesOfString:sharedManager.searchQuery];
NSString* foundHits = [webView stringByEvaluatingJavaScriptFromString:#"results"];
NSLog(#"%#", foundHits);
NSMutableArray* objects = [[NSMutableArray alloc] init];
NSArray* stringObjects = [foundHits componentsSeparatedByString:#";"];
for(int i=0; i<[stringObjects count]; i++){
NSArray* strObj = [[stringObjects objectAtIndex:i] componentsSeparatedByString:#","];
if([strObj count]==3){
[objects addObject:strObj];
}
}
NSArray* orderedRes = [objects sortedArrayUsingComparator:^(id obj1, id obj2){
int x1 = [[obj1 objectAtIndex:0] intValue];
int x2 = [[obj2 objectAtIndex:0] intValue];
int y1 = [[obj1 objectAtIndex:1] intValue];
int y2 = [[obj2 objectAtIndex:1] intValue];
if(y1<y2){
return NSOrderedAscending;
} else if(y1>y2){
return NSOrderedDescending;
} else {
if(x1<x2){
return NSOrderedAscending;
} else if (x1>x2){
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}
}];
[objects release];
for(int i=0; i<[orderedRes count]; i++){
NSArray* currObj = [orderedRes objectAtIndex:i];
SearchResult* searchRes = [[SearchResult alloc] initWithChapterIndex:currentChapterIndex pageIndex:([[currObj objectAtIndex:1] intValue]/webView.bounds.size.height) hitIndex:0 neighboringText:[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"unescape('%#')", [currObj objectAtIndex:2]]] originatingQuery:sharedManager.searchQuery];
[results addObject:searchRes];
[searchRes release];
}
[[self resultsTableView]reloadData];
//Print results
for(int i=0;i<[results count];i++)
{
hit = (SearchResult*)[results objectAtIndex:i];
}
[resultsTableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
if((currentChapterIndex+1)<[sharedManager.spineArray count]){
[self searchString:sharedManager.searchQuery inChapterAtIndex:(currentChapterIndex+1)];
} else {
fvc.searching= NO;
}
[[self resultsTableView]reloadData];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
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
{
[super viewDidLoad];
resultsTableView=[[UITableView alloc]init];
[resultsTableView setDelegate:self];
[resultsTableView setDataSource:self];
sharedManager=[Mymanager sharedManager];
// Do any additional setup after loading the view from its nib.
results = [[NSMutableArray alloc] init];
test=[[NSArray alloc]initWithObjects:#"one",#"one",#"one",#"one",nil];
self.navigationItem.title=#"Search ";
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle:#"Back"
style:UIBarButtonItemStylePlain
target:nil
action:nil];
self.navigationItem.backBarButtonItem=backButton;
[[UINavigationBar appearance] setTitleTextAttributes: #{
UITextAttributeTextColor: [UIColor whiteColor],
UITextAttributeTextShadowColor: [UIColor lightGrayColor],
UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)],
UITextAttributeFont: [UIFont fontWithName:#"Trebuchet MS" size:15.0f]
}];
[self searchString:sharedManager.searchQuery];
noMatchingSearch=[[NSArray alloc]initWithObjects:#"No Element Found", nil];
tableOfContents=[[NSMutableArray alloc]init];
for (id img in search.subviews)
{
if ([img isKindOfClass:NSClassFromString(#"UISearchBarBackground")])
{
[img removeFromSuperview];
}
}
tableOfContents=[sharedManager.List copy];
}
- (void)viewDidUnload
{
search = nil;
[super viewDidUnload];
resultsTableView.delegate=self;
resultsTableView.dataSource=self;
// Release any retained subviews of the main view.
self.resultsTableView = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
When you have received your search results call
[self.tableView reloadData];
To tell the table view to update itself. I can see you have tried it a number of times in the large amount of code above. You only need to call it once, when you have your search results ready. Also, ensure your reference to the table view is valid when you call it.
Also, if you're creating a table view in an XIB file, then the second one you're creating in viewDidLoad and not showing (adding as a subview) is just confusing you and you're trying to reload the wrong table view.
If you still have problems, show the class properties and remove all the code tat isn't to do with the table view.
resultsTableView=[[UITableView alloc]init];
Try to use resultsTableView, with a property, and set it's to (nonatomic, strong).

UITableview cellForRowAtIndexPath method is not executing?

When i click search it executes a search class and after finding the results it executes numberOfRows method but then it is showing empty table. It is not executing cellForRowAtIndexPath method .
check my below code
code in viewcontroller.h
when i click search button this method will get executed
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
SearchResultsViewController *searchRes=[[SearchResultsViewController alloc]initWithNibName:#"SearchResultsViewController" bundle:nil];
NSString *searchQuery=[search text];
sharedManager=[Mymanager sharedManager];
sharedManager.searchQuery=searchQuery;
[searchRes searchString:searchQuery];
[self.navigationController pushViewController:searchRes animated:YES];
}
in search class
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSLog(#"%#",results);
return [results count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.adjustsFontSizeToFitWidth = YES;
NSLog(#"indexpath%d",indexPath.row);
NSLog(#"%#",[results objectAtIndex:[indexPath row]]);
SearchResult* hit = (SearchResult*)[results objectAtIndex:[indexPath row]];
NSLog(#"%#",hit.neighboringText);
cell.textLabel.text = [NSString stringWithFormat:#"...%#...", hit.neighboringText];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Chapter %d - page %d", hit.chapterIndex, hit.pageIndex+1];
cell.textLabel.font = [UIFont fontWithName:#"Trebuchet MS" size:12];
cell.textLabel.textColor = [UIColor colorWithRed:25/255.0 green:90/255.0 blue:100/255.0 alpha:1];
// else
// {
//
// }
// [[self resultsTableView] reloadData];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
SearchResult* hit = (SearchResult*)[results objectAtIndex:[indexPath row]];
[fvc loadSpine:hit.chapterIndex atPageIndex:hit.pageIndex highlightSearchResult:hit];
}
- (void) searchString:(NSString*)query{
// if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
// {
self.results = [[NSMutableArray alloc] init];
[resultsTableView reloadData];
currentQuery=sharedManager.searchQuery;
//
[self searchString:currentQuery inChapterAtIndex:0];
//
// }else {
// currentQuery=sharedManager.searchQuery;
// [self searchString:currentQuery inChapterAtIndex:0];
//}
}
- (void) searchString:(NSString *)query inChapterAtIndex:(int)index{
currentChapterIndex = index;
sharedManager=[Mymanager sharedManager];
Chapter* chapter = [sharedManager.spineArray objectAtIndex:index];
NSLog(#"%d",chapter.text.length);
NSRange range = NSMakeRange(0, chapter.text.length);
NSLog(#"%#",sharedManager.searchQuery);
range = [chapter.text rangeOfString:sharedManager.searchQuery options:NSCaseInsensitiveSearch range:range locale:nil];
int hitCount=0;
while (range.location != NSNotFound) {
range = NSMakeRange(range.location+range.length, chapter.text.length-(range.location+range.length));
range = [chapter.text rangeOfString:sharedManager.searchQuery options:NSCaseInsensitiveSearch range:range locale:nil];
hitCount++;
}
if(hitCount!=0){
UIWebView* webView = [[UIWebView alloc] initWithFrame:chapter.windowSize];
[webView setDelegate:self];
NSURLRequest* urlRequest = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:chapter.spinePath]];
[webView loadRequest:urlRequest];
} else {
if((currentChapterIndex+1)<[sharedManager.spineArray count]){
[self searchString:sharedManager.searchQuery inChapterAtIndex:(currentChapterIndex+1)];
} else {
fvc.searching = NO;
}
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
NSLog(#"%#", error);
[webView release];
}
- (void) webViewDidFinishLoad:(UIWebView*)webView{
NSString *varMySheet = #"var mySheet = document.styleSheets[0];";
NSString *addCSSRule = #"function addCSSRule(selector, newRule) {"
"if (mySheet.addRule) {"
"mySheet.addRule(selector, newRule);" // For Internet Explorer
"} else {"
"ruleIndex = mySheet.cssRules.length;"
"mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex);" // For Firefox, Chrome, etc.
"}"
"}";
NSString *insertRule1 = [NSString stringWithFormat:#"addCSSRule('html', 'padding: 0px; height: %fpx; -webkit-column-gap: 0px; -webkit-column-width: %fpx;')", webView.frame.size.height, webView.frame.size.width];
NSString *insertRule2 = [NSString stringWithFormat:#"addCSSRule('p', 'text-align: justify;')"];
NSString *setTextSizeRule = [NSString stringWithFormat:#"addCSSRule('body', '-webkit-text-size-adjust: %d%%;')",[[sharedManager.spineArray objectAtIndex:currentChapterIndex] fontPercentSize]];
[webView stringByEvaluatingJavaScriptFromString:varMySheet];
[webView stringByEvaluatingJavaScriptFromString:addCSSRule];
[webView stringByEvaluatingJavaScriptFromString:insertRule1];
[webView stringByEvaluatingJavaScriptFromString:insertRule2];
[webView stringByEvaluatingJavaScriptFromString:setTextSizeRule];
[webView highlightAllOccurencesOfString:sharedManager.searchQuery];
NSString* foundHits = [webView stringByEvaluatingJavaScriptFromString:#"results"];
NSLog(#"%#", foundHits);
NSMutableArray* objects = [[NSMutableArray alloc] init];
NSArray* stringObjects = [foundHits componentsSeparatedByString:#";"];
for(int i=0; i<[stringObjects count]; i++){
NSArray* strObj = [[stringObjects objectAtIndex:i] componentsSeparatedByString:#","];
if([strObj count]==3){
[objects addObject:strObj];
}
}
NSArray* orderedRes = [objects sortedArrayUsingComparator:^(id obj1, id obj2){
int x1 = [[obj1 objectAtIndex:0] intValue];
int x2 = [[obj2 objectAtIndex:0] intValue];
int y1 = [[obj1 objectAtIndex:1] intValue];
int y2 = [[obj2 objectAtIndex:1] intValue];
if(y1<y2){
return NSOrderedAscending;
} else if(y1>y2){
return NSOrderedDescending;
} else {
if(x1<x2){
return NSOrderedAscending;
} else if (x1>x2){
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}
}];
[objects release];
NSLog(#"%#",currentQuery);
for(int i=0; i<[orderedRes count]; i++){
NSArray* currObj = [orderedRes objectAtIndex:i];
SearchResult* searchRes = [[SearchResult alloc] initWithChapterIndex:currentChapterIndex pageIndex:([[currObj objectAtIndex:1] intValue]/webView.bounds.size.height) hitIndex:0 neighboringText:[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"unescape('%#')", [currObj objectAtIndex:2]]] originatingQuery:currentQuery];
[results addObject:searchRes];
NSLog(#"%#",results);
[searchRes release];
}
//Print results
for(int i=0;i<[results count];i++)
{
SearchResult* hit = (SearchResult*)[results objectAtIndex:i];
NSLog(#"%#",hit.neighboringText);
}
[resultsTableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
if((currentChapterIndex+1)<[sharedManager.spineArray count]){
[self searchString:sharedManager.searchQuery inChapterAtIndex:(currentChapterIndex+1)];
} else {
fvc.searching= NO;
}
[[self resultsTableView] reloadData];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
//- (void)dealloc
////{
//// self.resultsTableView = nil;
//// //[results release];
//// //[currentQuery release];
//// [super dealloc];
//}
- (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
{
[super viewDidLoad];
resultsTableView=[[UITableView alloc]init];
[resultsTableView setDelegate:self];
[resultsTableView setDataSource:self];
sharedManager=[Mymanager sharedManager];
// Do any additional setup after loading the view from its nib.
results = [[NSMutableArray alloc] init];
self.navigationItem.title=#"Search ";
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle:#"Back"
style:UIBarButtonItemStylePlain
target:nil
action:nil];
self.navigationItem.backBarButtonItem=backButton;
[[UINavigationBar appearance] setTitleTextAttributes: #{
UITextAttributeTextColor: [UIColor whiteColor],
UITextAttributeTextShadowColor: [UIColor lightGrayColor],
UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)],
UITextAttributeFont: [UIFont fontWithName:#"Trebuchet MS" size:15.0f]
}];
noMatchingSearch=[[NSArray alloc]initWithObjects:#"No Element Found", nil];
tableOfContents=[[NSMutableArray alloc]init];
for (id img in search.subviews)
{
if ([img isKindOfClass:NSClassFromString(#"UISearchBarBackground")])
{
[img removeFromSuperview];
}
}
tableOfContents=[sharedManager.List copy];
}
- (void)viewDidUnload
{
search = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
self.resultsTableView = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
MY SEARCH RESULTS
"<SearchResult: 0x113482c0>",
"<SearchResult: 0x11348a20>",
"<SearchResult: 0x88c0a50>"
The problem is with the search method before search the array is reinitialised and hence 0 returned in the resultArray and hence no value in tables
- (void) searchString:(NSString*)query{
self.results = [[NSMutableArray alloc] init];//Here it becomes 0!!
[resultsTableView reloadData];
currentQuery=sharedManager.searchQuery;
}
To make it right ,After the search is performed i believe
[self searchString:currentQuery inChapterAtIndex:0];
load the value in the result array and then reload table.
Make sure
in .h add
<UITableViewDataSource,UITableViewDelegate>
in nib
connect datasource and delegate[if via nib]

Resources