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]
Related
I have added search bar for collection view using programatically .But when i enter the names to search nothing shows.I have some section also and each section contains some data.
Here is my code:
#interface ViewController ()
{
NSMutableArray *arrayPDFName;
NSMutableArray *titleArray;
}
#property (nonatomic,strong) NSArray *dataSourceForSearchResult;
#property (nonatomic) BOOL searchBarActive;
#property (nonatomic) float searchBarBoundsY;
#property (nonatomic,strong) UISearchBar *searchBar;
#property (nonatomic,strong) UIRefreshControl *refreshControl;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.dataSourceForSearchResult = [NSArray new];
titleArray = [NSMutableArray array];
[self getdata];
self.mycollectionView.dataSource = self;
self.mycollectionView.delegate = self;
[self.mycollectionView reloadData];
}
-(NSString*)sha256HashFor:(NSString*)input
{
const char* str = [input UTF8String];
unsigned char result[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(str, strlen(str), result);
NSMutableString *ret = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH*2];
for(int i = 0; i<CC_SHA256_DIGEST_LENGTH; i++)
{
[ret appendFormat:#"%02x",result[i]];
}
return ret;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self prepareUI];
}
-(void)getdata {
NSString *userName = #“username#yahoo.com";
NSString *password = #“password”;
NSData *plainData = [password dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
base64String=[self sha256HashFor: base64String];
NSString *urlString = #"https://api.exampleport/user/orderid/files";
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
// basic authendication
NSString *authStr = [NSString stringWithFormat:#"%#:%#", userName, base64String];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
//header-field
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64Encoding]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError * error;
self->arrayPDFName = [[NSMutableArray alloc]init];
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
NSDictionary *dictOriginal = jsonResults[#“dark”];
[titleArray addObject:[NSString stringWithFormat:#"dark(%#)”, dictOriginal[#"count"]]];
NSDictionary *dictOriginal2 = jsonResults[#"orange”];
[titleArray addObject:[NSString stringWithFormat:#"orange(%#)”, dictOriginal2[#"count"]]];
NSDictionary *dictOriginal3 = jsonResults[#"pencill”];
[titleArray addObject:[NSString stringWithFormat:#"pencill(%#)”, dictOriginal3[#"count"]]];
NSDictionary *dictOriginal4 = jsonResults[#"smart”];
[titleArray addObject:[NSString stringWithFormat:#"smart(%#)”, dictOriginal4[#"count"]]];
NSArray *arrayFiles = [NSArray arrayWithObjects: dictOriginal, dictOriginal2, dictOriginal3, dictOriginal4, nil];
NSLog(#"str: %#", titleArray);
for (NSDictionary *dict in arrayFiles) {
NSMutableArray *arr = [NSMutableArray array];
NSArray *a = dict[#"files"];
for(int i=0; i < a.count; i ++) {
NSString *strName = [NSString stringWithFormat:#"%#",[[dict[#"files"] objectAtIndex:i] valueForKey:#"name"]];
// NSLog(#"str: %#", strName);
[arr addObject:strName];
}
[arrayPDFName addObject:arr];
}
//Get plist path
NSString *errorDesc;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths objectAtIndex:0];
NSString *plistPath = [documentsDirectory1 stringByAppendingPathComponent:#"SampleData.plist"];
//NSLog(#"plistPath : %#",plistPath);
//Save data from json to plist
NSString *error1;
returnData = [NSPropertyListSerialization dataFromPropertyList:jsonResults
format:NSPropertyListXMLFormat_v1_0
errorDescription:&error];
if(returnData ) {
if ([returnData writeToFile:plistPath atomically:YES]) {
NSLog(#"Data successfully saved.");
}else {
NSLog(#"Did not managed to save NSData.");
}
}
else {
NSLog(#"%#",errorDesc);
}
// NSArray *stringsArray = [NSArray arrayWithContentsOfFile:plistPath];
NSDictionary *stringsDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];
// NSLog(#"str: %#", stringsDictionary);
}
//delegate method for header
-(UICollectionReusableView*) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
HeaderView * header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:#"myHeader" forIndexPath:indexPath];
header.myHeaderLabel.text = titleArray[indexPath.section];
return header;
}
#pragma mark - UICollectionView Datasource
-(NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return titleArray.count;
}
-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
if (self.searchBarActive) {
return self.dataSourceForSearchResult.count;
}
NSArray *a = arrayPDFName[section];
if (a.count == 0)
{
return 1;
}
else
{
return a.count;
}
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
return CGSizeMake(0, 80);
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath: (NSIndexPath *)indexPath {
VenueCell *cell = [cv dequeueReusableCellWithReuseIdentifier:#"mycell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor whiteColor];
cell.imgV.image = [UIImage imageNamed:#"doc1.png"];
if (self.searchBarActive) {
cell.myLabel.text = _dataSourceForSearchResult[indexPath.section][indexPath.row];
}else{
NSArray *a = arrayPDFName[indexPath.section];
if (a.count == 0) {
cell.myLabel.text = #"NO DATA";
return cell;
}
cell.myLabel.text = a[indexPath.row];
}
return cell;
}
//////////////////////////for search bar //////////
#pragma mark - actions
-(void)refreashControlAction{
[self cancelSearching];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// stop refreshing after 2 seconds
[self.mycollectionView reloadData];
[self.refreshControl endRefreshing];
});
}
#pragma mark - search
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"self contains[c] %#", searchText];
self.dataSourceForSearchResult = [self->arrayPDFName filteredArrayUsingPredicate:resultPredicate];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
// user did type something, check our datasource for text that looks the same
if (searchText.length>0) {
// search and reload data source
self.searchBarActive = YES;
[self filterContentForSearchText:searchText
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
[self.mycollectionView reloadData];
}else{
// if text lenght == 0
// we will consider the searchbar is not active
self.searchBarActive = NO;
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
[self cancelSearching];
[self.mycollectionView reloadData];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
self.searchBarActive = YES;
[self.view endEditing:YES];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
// we used here to set self.searchBarActive = YES
// but we'll not do that any more... it made problems
// it's better to set self.searchBarActive = YES when user typed something
[self.searchBar setShowsCancelButton:YES animated:YES];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
// this method is being called when search btn in the keyboard tapped
// we set searchBarActive = NO
// but no need to reloadCollectionView
self.searchBarActive = NO;
[self.searchBar setShowsCancelButton:NO animated:YES];
}
-(void)cancelSearching{
self.searchBarActive = NO;
[self.searchBar resignFirstResponder];
self.searchBar.text = #"";
}
#pragma mark - prepareVC
-(void)prepareUI{
[self addSearchBar];
[self addRefreshControl];
}
-(void)addSearchBar{
if (!self.searchBar) {
self.searchBarBoundsY = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,self.searchBarBoundsY, [UIScreen mainScreen].bounds.size.width, 50)];
self.searchBar.searchBarStyle = UISearchBarStyleMinimal;
self.searchBar.tintColor = [UIColor whiteColor];
self.searchBar.barTintColor = [UIColor whiteColor];
self.searchBar.delegate = self;
self.searchBar.placeholder = #"Search here";
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor whiteColor]];
// add KVO observer.. so we will be informed when user scroll colllectionView
[self addObservers];
}
if (![self.searchBar isDescendantOfView:self.view]) {
[self.view addSubview:self.searchBar];
}
}
-(void)addRefreshControl{
if (!self.refreshControl) {
self.refreshControl = [UIRefreshControl new];
self.refreshControl.tintColor = [UIColor whiteColor];
[self.refreshControl addTarget:self
action:#selector(refreashControlAction)
forControlEvents:UIControlEventValueChanged];
}
if (![self.refreshControl isDescendantOfView:self.mycollectionView]) {
[self.mycollectionView addSubview:self.refreshControl];
}
}
-(void)startRefreshControl{
if (!self.refreshControl.refreshing) {
[self.refreshControl beginRefreshing];
}
}
Where i am doing mistake and what i need to change to work.Thanks in advance!
It seems your arrayPDFName have array object and each array object have string object. There are two ways to filter you array.
Way - 1
If you want to get the list of array which has the search string the use SUBQUERY with your predicate. Like below.
NSArray *a1 = #[#"a1", #"a2", #"a3"];
NSArray *a2 = #[#"a1", #"a2", #"a3"];
NSArray *a3 = #[#"a1", #"a2", #"a3"];
NSArray *a4 = #[#"a2", #"a3"];
NSArray *allA = #[a1, a2, a3, a4];
NSPredicate *pre = [NSPredicate predicateWithFormat:#"SUBQUERY(SELF, $a, $a == %#).#count > 0", #"a1"];
NSArray *a = [allA filteredArrayUsingPredicate:pre];
Way - 2
If you want to get the search string alone from each array object then follow the below,
NSMutableArray *fa = [[NSMutableArray alloc] init];
for (NSArray *a in allA) {
NSPredicate *p = [NSPredicate predicateWithFormat:#"self CONTAINS[c] %#", #"a3"];
[fa addObjectsFromArray:[a filteredArrayUsingPredicate:p]];
}
Note: Above code done with same sample data. Replace it as you want.
As per your code replace the below code
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
NSMutableArray *fa = [[NSMutableArray alloc] init];
for (NSArray *a in arrayPDFName) {
NSPredicate *p = [NSPredicate predicateWithFormat:#"self CONTAINS[c] %#", searchText];
[fa addObjectsFromArray:[a filteredArrayUsingPredicate:p]];
}
self.dataSourceForSearchResult = [NSArray arrayWithArray:fa];
}
-(NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
if(self.searchBarActive)
return 1;
return titleArray.count;
}
In cellForItemAtIndexPath
cell.myLabel.text = _dataSourceForSearchResult[indexPath.row];
Hi My data is getting duplicated every time I use the pull to refresh.. for eg. 5 initial entries in the table view are doubled to 10 with one pull to refresh and adding 5 more in the subsequent pull to refresh. How can I stop the duplication.. I would like to make sure that only new items are downloaded and existing data in the table is not downloaded again.
#implementation RootViewController
#synthesize allEntries = _allEntries;
#synthesize feeds = _feeds;
#synthesize queue = _queue;
#synthesize webViewController = _webViewController;
#pragma mark -
#pragma mark View lifecycle
- (void)addRows {
RSSEntry *entry1 = [[[RSSEntry alloc] initWithBlogTitle:#"1"
articleTitle:#"1"
articleUrl:#"1"
articleDate:[NSDate date]] autorelease];
RSSEntry *entry2 = [[[RSSEntry alloc] initWithBlogTitle:#"2"
articleTitle:#"2"
articleUrl:#"2"
articleDate:[NSDate date]] autorelease];
RSSEntry *entry3 = [[[RSSEntry alloc] initWithBlogTitle:#"3"
articleTitle:#"3"
articleUrl:#"3"
articleDate:[NSDate date]] autorelease];
[_allEntries insertObject:entry1 atIndex:0];
[_allEntries insertObject:entry2 atIndex:0];
[_allEntries insertObject:entry3 atIndex:0];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Songs";
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feeds = [NSArray arrayWithObjects:
#"http://hindisongs.bestofindia.co/?feed=rss2",
nil];
self.refreshControl = [UIRefreshControl new];
self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:#"Pull to refresh"];
[self.refreshControl addTarget:self action:#selector(bindDatas) forControlEvents:UIControlEventValueChanged];
[self bindDatas]; //called at the first time
}
-(void)bindDatas
{
//GET YOUR DATAS HERE…
for (NSString *feed in _feeds) {
NSURL *url = [NSURL URLWithString:feed];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[_queue addOperation:request];
}
//update the tableView
[self.tableView reloadData];
if(self.refreshControl != nil && self.refreshControl.isRefreshing == TRUE)
{
[self.refreshControl endRefreshing];
}
}
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"link"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate] autorelease];
[entries addObject:entry];
}
}
}
- (void)parseAtom:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSString *blogTitle = [rootElement valueForChild:#"title"];
NSArray *items = [rootElement elementsForName:#"entry"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = nil;
NSArray *links = [item elementsForName:#"link"];
for(GDataXMLElement *link in links) {
NSString *rel = [[link attributeForName:#"rel"] stringValue];
NSString *type = [[link attributeForName:#"type"] stringValue];
if ([rel compare:#"alternate"] == NSOrderedSame &&
[type compare:#"text/html"] == NSOrderedSame) {
articleUrl = [[link attributeForName:#"href"] stringValue];
}
}
NSString *articleDateString = [item valueForChild:#"updated"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC3339];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate] autorelease];
[entries addObject:entry];
}
}
- (void)parseFeed:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
[self parseRss:rootElement entries:entries];
} else if ([rootElement.name compare:#"feed"] == NSOrderedSame) {
[self parseAtom:rootElement entries:entries];
} else {
NSLog(#"Unsupported root element: %#", rootElement.name);
}
}
- (void)requestFinished:(ASIHTTPRequest *)request {
[_queue addOperationWithBlock:^{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil) {
NSLog(#"Failed to parse %#", request.url);
} else {
NSMutableArray *entries = [NSMutableArray array];
[self parseFeed:doc.rootElement entries:entries];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries) {
int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
RSSEntry *entry1 = (RSSEntry *) a;
RSSEntry *entry2 = (RSSEntry *) b;
return [entry1.articleDate compare:entry2.articleDate];
}];
[_allEntries insertObject:entry atIndex:insertIdx];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
withRowAnimation:UITableViewRowAnimationRight];
}
}];
}
}];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
NSError *error = [request error];
NSLog(#"Error: %#", error);
}
/*
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_allEntries count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
cell.textLabel.text = entry.articleTitle;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%# - %#", articleDateString, entry.blogTitle];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source.
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (_webViewController == nil) {
self.webViewController = [[[WebViewController alloc] initWithNibName:#"WebViewController" bundle:[NSBundle mainBundle]] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
_webViewController.entry = entry;
[self.navigationController pushViewController:_webViewController animated:YES];
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
self.webViewController = nil;
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[_allEntries release];
_allEntries = nil;
[_queue release];
_queue = nil;
[_feeds release];
_feeds = nil;
[_webViewController release];
_webViewController = nil;
[super dealloc];
}
The issue is that you keep inserting object to _allEntries without ever reseting it. You will want to empty it out at some point, either when the user pulls to refresh or when the new data comes in before you add any new objects to it.
[_allEntries removeAllObjects];
Try putting it at the start of bindDatas.
Thanks to #jsetting32 I have a custom UITableViewCell complete with buttons at the bottom of the tableView. However, when I am clicking those buttons, the value for the selectedState is not changing, making it a bit difficult for the end-user to tell if they have clicked it or not.
self.likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.likeButton addTarget:self action:#selector(didTapLikeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.likeButton setTitle:#"Pray" forState:UIControlStateNormal];
[self.likeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.likeButton setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
[[self.likeButton titleLabel] setFont:[UIFont fontWithName:#"Verdana" size:12.0f]];
[self.cellView addSubview:self.likeButton];
Try UIControlStateHighlighted instead of UIControlStateSelected
[self.likeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.likeButton setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
So heres how I solve the button issue... There should already be a method within your custom cell that sets the like status... It is set like so
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cellIdentifier";
if (indexPath.row == [self.objects count])
return [self tableView:tableView cellForNextPageAtIndexPath:indexPath];
PHChatCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[PHChatCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
[cell setDelegate:self];
}
[self setCellAttributesWithCell:cell withObject:[self.object objectAtIndex:indexPath.row] withIndexPath:indexPath];
return cell;
}
- (void)setCellAttributesWithCell:(PHChatCell *)cell withObject:(PFObject *)object withIndexPath:(NSIndexPath *)indexPath
{
if (object) {
[cell setChat:object];
[cell setTag:indexPath.row];
[cell.likeButton setTag:indexPath.row];
if ([[PHCache sharedCache] attributesForMessage:object]) {
[cell setLikeStatus:[[PHCache sharedCache] isMessageLikedByCurrentUser:object]];
NSString *likeCount = [[[PHCache sharedCache] likeCountForMessage:object] description];
cell.likeCount.text = ([likeCount isEqualToString:#"1"]) ?
[NSString stringWithFormat:#"%# like", likeCount] :
[NSString stringWithFormat:#"%# likes", likeCount];
NSString *commentCount = [[[PHCache sharedCache] commentCountForMessage:object] description];
cell.commentCount.text = ([commentCount isEqualToString:#"1"]) ?
[NSString stringWithFormat:#"%# comment", commentCount] :
[NSString stringWithFormat:#"%# comments", commentCount];
return;
}
#synchronized(self) {
// Put this in your init method
// self.outstandingSectionHeadersQueries = [NSMutableDictionary dictionary]
if (![self.outstandingSectionHeaderQueries objectForKey:#(indexPath.row)]) {
PFQuery *query = [PHUtility queryForActivitiesOnMessage:object cachePolicy:kPFCachePolicyNetworkOnly];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
#synchronized(self) {
[self.outstandingSectionHeaderQueries removeObjectForKey:#(indexPath.row)];
if (error) return;
NSMutableArray *likers = [NSMutableArray array];
NSMutableArray *commenters = [NSMutableArray array];
BOOL isLikedByCurrentUser = NO;
for (PFObject *activity in objects) {
if ([[activity objectForKey:kPHActivityTypeKey] isEqualToString:kPHActivityTypeLike] && [activity objectForKey:kPHActivityFromUserKey]) {
[likers addObject:[activity objectForKey:kPHActivityFromUserKey]];
} else if ([[activity objectForKey:kPHActivityTypeKey] isEqualToString:kPHActivityTypeComment] && [activity objectForKey:kPHActivityFromUserKey]) {
[commenters addObject:[activity objectForKey:kPHActivityFromUserKey]];
}
if ([[[activity objectForKey:kPHActivityFromUserKey] objectId] isEqualToString:[[PFUser currentUser] objectId]] &&
[[activity objectForKey:kPHActivityTypeKey] isEqualToString:kPHActivityTypeLike]) {
isLikedByCurrentUser = YES;
}
}
[[PHCache sharedCache] setAttributesForMessage:object likers:likers commenters:commenters likedByCurrentUser:isLikedByCurrentUser];
if (cell.tag != indexPath.row) return;
[cell setLikeStatus:[[PHCache sharedCache] isMessageLikedByCurrentUser:object]];
NSString *likeCount = [[[PHCache sharedCache] likeCountForMessage:object] description];
cell.likeCount.text = ([likeCount isEqualToString:#"1"]) ?
[NSString stringWithFormat:#"%# like", likeCount] : [NSString stringWithFormat:#"%# likes", likeCount];
NSString *commentCount = [[[PHCache sharedCache] commentCountForMessage:object] description];
cell.commentCount.text = ([commentCount isEqualToString:#"1"]) ?
[NSString stringWithFormat:#"%# comment", commentCount] : [NSString stringWithFormat:#"%# comments", commentCount];
}
}];
}
}
}
}
- (void)PHChatCell:(PHChatCell *)cell didTapLikeButton:(UIButton *)button chat:(PFObject *)chat
{
// Disable the button so users cannot send duplicate requests
[cell shouldEnableLikeButton:NO];
//These are private interface properties to handle when the user wants to unlike the prayer
//when the UIActionsheet is loaded
self.chat = chat;
self.likeButton = button;
self.cell = cell;
if (button.selected) {
[[[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:#"Unlike" otherButtonTitles:nil] showInView:self.view];
return;
}
BOOL liked = !button.selected;
[cell setLikeStatus:liked];
NSString *originalButtonTitle = button.titleLabel.text;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]];
NSNumber *likeCount = [numberFormatter numberFromString:button.titleLabel.text];
[button setTitle:#"Liked" forState:UIControlStateNormal];
[UIView animateWithDuration:0.25 animations:^{
[cell.likeImage setImage:[UIImage imageNamed:#"ButtonLikeSelected.png"]];
[cell.likeImage setTransform:CGAffineTransformMakeScale(1.5, 1.5)];
} completion:^(BOOL finished){
[UIView animateWithDuration:0.25 animations:^{
[cell.likeImage setTransform:CGAffineTransformMakeScale(1, 1)];
}];
}];
NSInteger checker = [[cell.likeCount text] integerValue] + 1;
cell.likeCount.text = (checker == 1) ?
[NSString stringWithFormat:#"%ld like", (long)checker] :
[NSString stringWithFormat:#"%ld likes", (long)checker];
likeCount = [NSNumber numberWithInt:[likeCount intValue] + 1];
[[PHCache sharedCache] incrementLikerCountForMessage:chat];
[[PHCache sharedCache] setMessageIsLikedByCurrentUser:chat liked:liked];
[PHUtility likeMessageInBackground:chat block:^(BOOL succeeded, NSError *error) {
PHChatCell *actualCell = (PHChatCell *)[self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:button.tag inSection:0]];
[actualCell shouldEnableLikeButton:YES];
[actualCell setLikeStatus:succeeded];
if (!succeeded) {
[actualCell.likeButton setTitle:originalButtonTitle forState:UIControlStateNormal];
}
}];
}
#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) {
BOOL liked = !self.likeButton.selected;
[self.cell setLikeStatus:liked];
[self.likeButton setTitle:#"Like" forState:UIControlStateNormal];
[self.cell.likeImage setImage:[UIImage imageNamed:#"ButtonLike.png"]];
NSInteger checker = [[self.cell.likeCount text] integerValue] - 1;
self.cell.likeCount.text = (checker == 1) ?
[NSString stringWithFormat:#"%ld like", (long)checker] :
[NSString stringWithFormat:#"%ld likes", (long)checker];
NSString *originalButtonTitle = self.likeButton.titleLabel.text;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSNumber *likeCount = [numberFormatter numberFromString:self.likeButton.titleLabel.text];
likeCount = [NSNumber numberWithInt:[likeCount intValue] + 1];
if ([likeCount intValue] > 0) {
likeCount = [NSNumber numberWithInt:[likeCount intValue] - 1];
}
[[PHCache sharedCache] decrementLikerCountForMessage:self.chat];
[[PHCache sharedCache] setMessageIsLikedByCurrentUser:self.chat liked:NO];
[PHUtility unlikeMessageInBackground:self.chat block:^(BOOL succeeded, NSError *error) {
PHChatCell *actualCell = (PHChatCell *)[self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.likeButton.tag inSection:0]];
[actualCell shouldEnableLikeButton:YES];
[actualCell setLikeStatus:!succeeded];
if (!succeeded) {
[actualCell.likeButton setTitle:originalButtonTitle forState:UIControlStateNormal];
}
}];
}
}
Here is the query method used in the previous snippet of code (declared in PHUtility class) :
+ (PFQuery *)queryForActivitiesOnMessage:(PFObject *)message cachePolicy:(PFCachePolicy)cachePolicy {
PFQuery *queryLikes = [PFQuery queryWithClassName:kPHActivityClassKey];
[queryLikes whereKey:kPHActivityMessageKey equalTo:message];
[queryLikes whereKey:kPHActivityTypeKey equalTo:kPHActivityTypeLike];
PFQuery *queryComments = [PFQuery queryWithClassName:kPHActivityClassKey];
[queryComments whereKey:kPHActivityMessageKey equalTo:message];
[queryComments whereKey:kPHActivityTypeKey equalTo:kPHActivityTypeComment];
PFQuery *query = [PFQuery orQueryWithSubqueries:[NSArray arrayWithObjects:queryLikes,queryComments,nil]];
[query setCachePolicy:cachePolicy];
[query includeKey:kPHActivityFromUserKey];
[query includeKey:kPHActivityMessageKey];
return query;
}
Here are the PHCache implementation ...
#interface PHCache()
#property (nonatomic, strong) NSCache *cache;
- (void)setAttributes:(NSDictionary *)attributes forMessage:(PFObject *)message;
#end
#implementation PHCache
#synthesize cache;
#pragma mark - Initialization
+ (id)sharedCache {
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init];
});
return _sharedObject;
}
- (id)init {
self = [super init];
if (self) {
self.cache = [[NSCache alloc] init];
}
return self;
}
- (void)clear {
[self.cache removeAllObjects];
}
- (void)setAttributes:(NSDictionary *)attributes forMessage:(PFObject *)message {
[self.cache setObject:attributes forKey:[self keyForMessage:message]];
}
- (NSString *)keyForMessage:(PFObject *)message {
return [NSString stringWithFormat:#"message_%#", [message objectId]];
}
#pragma mark - Global Chat
- (void)setAttributesForMessage:(PFObject *)message
likers:(NSArray *)likers
commenters:(NSArray *)commenters
likedByCurrentUser:(BOOL)likedByCurrentUser {
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:likedByCurrentUser],kPHMessageAttributesIsLikedByCurrentUserKey,
#([likers count]),kPHMessageAttributesLikeCountKey,
likers,kPHMessageAttributesLikersKey,
#([commenters count]),kPHMessageAttributesCommentCountKey,
commenters,kPHMessageAttributesCommentersKey,
nil];
[self setAttributes:attributes forMessage:message];
}
- (NSDictionary *)attributesForMessage:(PFObject *)message {
return [self.cache objectForKey:[self keyForMessage:message]];
}
- (NSNumber *)likeCountForMessage:(PFObject *)message {
NSDictionary *attributes = [self attributesForMessage:message];
if (attributes) {
return [attributes objectForKey:kPHMessageAttributesLikeCountKey];
}
return [NSNumber numberWithInt:0];
}
- (NSNumber *)commentCountForMessage:(PFObject *)message {
NSDictionary *attributes = [self attributesForMessage:message];
if (attributes) {
return [attributes objectForKey:kPHMessageAttributesCommentCountKey];
}
return [NSNumber numberWithInt:0];
}
- (NSArray *)likersForMessage:(PFObject *)message {
NSDictionary *attributes = [self attributesForMessage:message];
if (attributes) {
return [attributes objectForKey:kPHMessageAttributesLikersKey];
}
return [NSArray array];
}
- (NSArray *)commentersForMessage:(PFObject *)message {
NSDictionary *attributes = [self attributesForMessage:message];
if (attributes) {
return [attributes objectForKey:kPHMessageAttributesCommentersKey];
}
return [NSArray array];
}
- (void)setMessageIsLikedByCurrentUser:(PFObject *)message liked:(BOOL)liked {
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
[attributes setObject:[NSNumber numberWithBool:liked] forKey:kPHMessageAttributesIsLikedByCurrentUserKey];
[self setAttributes:attributes forMessage:message];
}
- (BOOL)isMessageLikedByCurrentUser:(PFObject *)message {
NSDictionary *attributes = [self attributesForMessage:message];
if (attributes) {
return [[attributes objectForKey:kPHMessageAttributesIsLikedByCurrentUserKey] boolValue];
}
return NO;
}
- (void)incrementLikerCountForMessage:(PFObject *)message {
NSNumber *likerCount = [NSNumber numberWithInt:[[self likeCountForMessage:message] intValue] + 1];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
[attributes setObject:likerCount forKey:kPHMessageAttributesLikeCountKey];
[self setAttributes:attributes forMessage:message];
}
- (void)decrementLikerCountForMessage:(PFObject *)message {
NSNumber *likerCount = [NSNumber numberWithInt:[[self likeCountForMessage:message] intValue] - 1];
if ([likerCount intValue] < 0) {
return;
}
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
[attributes setObject:likerCount forKey:kPHMessageAttributesLikeCountKey];
[self setAttributes:attributes forMessage:message];
}
- (void)incrementCommentCountForMessage:(PFObject *)message {
NSNumber *commentCount = [NSNumber numberWithInt:[[self commentCountForMessage:message] intValue] + 1];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
[attributes setObject:commentCount forKey:kPHMessageAttributesCommentCountKey];
[self setAttributes:attributes forMessage:message];
}
- (void)decrementCommentCountForMessage:(PFObject *)message {
NSNumber *commentCount = [NSNumber numberWithInt:[[self commentCountForMessage:message] intValue] - 1];
if ([commentCount intValue] < 0) {
return;
}
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
[attributes setObject:commentCount forKey:kPHMessageAttributesCommentCountKey];
[self setAttributes:attributes forMessage:message];
}
- (NSNumber *)messageCountForUser:(PFUser *)user {
NSDictionary *attributes = [self attributesForUser:user];
if (attributes) {
NSNumber *photoCount = [attributes objectForKey:kPHUserAttributesMessageCountKey];
if (photoCount) {
return photoCount;
}
}
return [NSNumber numberWithInt:0];
}
- (void)setMessageCount:(NSNumber *)count user:(PFUser *)user {
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForUser:user]];
[attributes setObject:count forKey:kPHUserAttributesMessageCountKey];
[self setAttributes:attributes forUser:user];
}
Like I said in your previous post... It requires a hefty amount of code to make this feature 'optimal'... Reason for the cache object is to limit api requests to the servers. If the cell has been loaded, we're gonna check the cache to see if the attributes for the cell have been loaded, if it hasn't query to the server to get the attributes and set the cache to ensure we don't need to make an api request in the future...
All the variables starting with kPH are constants that you can declare on your own, or how you feel is sufficient... Like I said before, checking out the Anypic project and integrating the features into your app is best. Just copy over the PAPCache class and PAPUtility class over. Just make sure you read over the code to fully understand what is going on to get a better sense of how to integrate the code with yours, and to extend it to add more features to your app.
If you have any issues please feel free to post a comment.
i. While touching use UIControlStateHighlighted as suggested above.
ii. Keep a different color:
Since you have a custom UITableViewCell, you should implement an IBAction and set your UIButton to this using
[self.likeButton addTarget:self action:#selector(select:) forControlEvents:UIControlEventTouchUpInside];
in the .m file of your cell set:
-(IBAction)onSelectCellClicked:(id)sender {
if(self.yourButton.selected) {
self.yourButton.selected = NO;
} else {
self.yourButton.selected = YES;
}
}
Now set the cell's delegate to self in cell for row after putting this in the cell's .h file:
#protocol CustomCellDelegate <NSObject>
#end
#interface CustomCell : UITableViewCell
#property (strong, nonatomic) NSObject<CustomCellDelegate>* delegate;
#end
And put in the VC that is presenting the UITableView using the custom cell.
you can just add this line into 'didTapLikeButtonAction' :
self.likeButton.selected = !self.likeButton.selected;
once you change the selected state, the button will change its title color.
you may also want to add this line for a smoother effect:
[self.likeButton setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
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.
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).