How to show my url json data to collection view - ios

I have get data from one url with authorized header and i convert to json.
In my json i am having only pdf file. But i don't want to show pdf file. I want to show the file name ( eg : document1.pdf, document2.pdf ).and also i am having 3 section - each contain 10 documents. So i need to show name of the document.
I saw some tutorials which using only image not document file. So how to show my document name alone to collection view.
One more question. does i need to decode to show my data or don't want to do that. Help me out.Thanks in advance !

NSMutableArry *arrayPDFName = [[NSMutableArray alloc]init];
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
NSDictionary *dictOriginal = [jsonResultsvalueForKey:#"original"];
NSArray *arrayFiles = [[dictOriginal valueForKey:#"files"] copy];
NSLog(#"The arrayFiles are - %#",arrayFiles);
for(int i=0;i<[arrayFiles count];i++)
{
NSString *strCreatedTime = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:i] valueForKey:#"created_time"]];
NSString *strLastModifiedTime = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:i] valueForKey:#"last_modified_time"]];
NSString *strID = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:i] valueForKey:#"id"]];
NSString *strName = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:i] valueForKey:#"name"]];
NSLog(#"The created_time is - %#",strCreatedTime);
NSLog(#"The last_modified_time is - %#",strLastModifiedTime);
NSLog(#"The is is - %#",strID);
NSLog(#"The name is - %#",strName);
[arrayPDFName addObject:strName];
}
}
in collectionview you need use the above arrayPDFName(in collection view delegates methods)
Showing data in CollectionView
- (void)viewDidLoad
{
[super viewDidLoad];
[self getResponse];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
//Register the custom cell for collection view
UINib *cellNib = [UINib nibWithNibName:#"CustomCell" bundle:nil];
[collectionViewHorizontalVertical registerNib:cellNib forCellWithReuseIdentifier:#"cvCell"];
}
//Collection View Delegates method
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return arrayPDFName.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"cvCell";
CustomCell *cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
//data for text
cell.textField.text = [arrayPDFName objectAtIndex:indexPath.row];
//OR Image
cell.imgViewCollection.image = [UIImage imageNamed:[arrayPDFName objectAtIndex:indexPath.row]];
return cell;
}
// If you want to set the cell height
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(200, 200); //Please give your required size
}

Related

Dynamic UITableViewCell height for a cell that contains a UIWebView in iOS

What I'm trying to do is load some HTML resource files in to UITableView cells. I wanted to adjust the cell heights depend on the content size of the UIWebView. Following is some of my test codes.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"TableCellID";
CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:#"CustomTableViewCell" owner:self options:nil];
cell = [nibArray objectAtIndex:0];
}
NSString *htmlFileName = [NSString stringWithFormat:#"page%ld", (long)indexPath.row];
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:htmlFileName ofType:#"html"];
NSString *htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[cell.webView loadHTMLString:htmlString baseURL: [[NSBundle mainBundle] bundleURL]];
return cell;
}
If I describe my CustomTableViewCell.xib, it has a UIWebView inside the Content View and UIWebView has following constraints given.
ContentView.Bottom = WebView.Bottom + 8
ContentView.Top = WebView.Top +8
ContentView.Leading = WebView.Leading + 8
ContentView.Trailing = WebView.Trailing + 8
HTML fils has no JavaScript or CSS content. Simple as below.
<html>
<header>
</header>
<body>
<p>eeeee eeeee eeeee eeeee eeeee eeeee eeeee eeeee eeeee eeeee</p>
</body>
</html>
Now my out put is like below image.
As I explained at top, my web pages doesn't contain any JavaScript. So I may not able to use stringByEvaluatingJavaScriptFromString method to return the text.
Try this
- (void)viewDidLoad {
[super viewDidLoad];
arrOfHTMLList= [[NSMutableArray alloc] init];
NSMutableDictionary *dic1 = [[NSMutableDictionary alloc] init];
[dic1 setObject:#"0" forKey:#"height"];
[dic1 setObject:#"aaaaaaaaaa aaaaaa aaaaaaa aaaaaaa aaaaaa aaaaaa aaaaaaaa aaaaa" forKey:#"htmlString"];
NSMutableDictionary *dic2 = [[NSMutableDictionary alloc] init];
[dic1 setObject:#"0" forKey:#"height"];
[dic1 setObject:#"abababababbabababababab ababab bababa ababababb" forKey:#"htmlString"];
NSMutableDictionary *dic3 = [[NSMutableDictionary alloc] init];
[dic1 setObject:#"0" forKey:#"height"];
[dic1 setObject:#"sdajdkjas dkasjkhd jkashjkd sakjhdkj askjdaksh dksajkdkjsah djkasjkhd kjsahjkd asjkhdk jasjkdhaskj" forKey:#"htmlString"];
NSMutableDictionary *dic4 = [[NSMutableDictionary alloc] init];
[dic1 setObject:#"0" forKey:#"height"];
[dic1 setObject:#"sdajdkjas dkasjkhd jkashjkd sakjhdkj askjdaksh dksajkdkjsah djkasjkhd kjsahjkd asjkhdk jasjkdhaskj" forKey:#"htmlString"];
[arrOfHTMLList addObject:dic1];
[arrOfHTMLList addObject:dic2];
[arrOfHTMLList addObject:dic3];
[arrOfHTMLList addObject:dic4];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
UIWebView *webView = (UIWebView*)[cell viewWithTag:1];
NSString *myHTML = arrOfHTMLList[indexPath.section][#"htmlString"];
[webView loadHTMLString:myHTML baseURL:nil];
webView.delegate = self;
webView.frame = CGRectMake(0, 0, screenWidth,cell.frame.size.height);
return cell;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
for (UIView *parent=[webView superview];parent!=nil ;parent=[parent superview] )
{
if([parent isKindOfClass:[UITableViewCell class]])
{
UITableViewCell *cell=(UITableViewCell *)parent;
NSIndexPath *indexPath=[_tableView indexPathForCell:cell];
int height = webView.scrollView.contentSize.height;
[[arrOfHTMLList objectAtIndex:indexPath.section] setObject:[NSString stringWithFormat:#"%d",height] forKey:#"height"];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGFloat height = [arrOfHTMLList[indexPath.section][#"height"] intValue];
return height;
}
Hope it helps.
the main issue is to get a web view's frame to adapt to its html content right away :)
and THAT only happens after it asynchronously loaded the content!
- (void)webViewDidFinishLoad:(UIWebView *)aWebView {
//TODO: update the table's height for the cell for the webview
}
a drop-in solution I wrote is a custom UITableViewCell subclass that has a webview and informs a delegate to reload the table:
https://github.com/Daij-Djan/DDUtils/tree/master/objC/DDUtils-IOS/ui/M42WebviewTableViewCell%20%5Bios%5D
the most important piece of code is:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
M42WebviewTableViewCell *cell = _loadedCells[#(indexPath.row)];
if (!cell) {
cell = [[M42WebviewTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
NSString *object = _objects[indexPath.row];
cell.tag = indexPath.row;
cell.delegate = self;
[cell setHtml:object AndBaseURL:nil];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//if a cell isnt ready, it wont be there and the method will return 0
M42WebviewTableViewCell *cell = _loadedCells[#(indexPath.row)];
return cell.height;
}
#pragma mark - M42WebviewTableViewCellDelegate
- (void)tableCellDidLoadContent:(M42WebviewTableViewCell *)cell {
if (!_loadedCells) {
_loadedCells = [[NSMutableDictionary alloc] init];
}
[_loadedCells setObject:cell forKey:#(cell.tag)];
//only refresh sizes of rows
[self.tableView beginUpdates];
[self.tableView endUpdates];
}
I came up with my own solution. But thanks all the others who commented on this question and open my mind in different paths. So here what I did.
First added a UIWebViewDelegate to my ViewController class
#interface ViewController () <UITableViewDataSource, UITableViewDelegate, UIWebViewDelegate> {
Then loading HTML pages and adding delegate is done inside following method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"TableCellID";
CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:#"CustomTableViewCell" owner:self options:nil];
cell = [nibArray objectAtIndex:0];
}
cell.webView.delegate = self;
cell.webView.tag = indexPath.row;
cell.webView.scrollView.scrollEnabled = NO;
NSString *htmlFileName = [NSString stringWithFormat:#"page%ld", (long)indexPath.row];
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:htmlFileName ofType:#"html"];
NSString *htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[cell.webView loadHTMLString:htmlString baseURL: [[NSBundle mainBundle] bundleURL]];
return cell;
}
After web view is loaded, calculate the size that fits to it's content and after all web views are loaded, I reload table data like below.
- (void)webViewDidFinishLoad:(UIWebView *)webView {
if (webView.tag == 0) {
[cellHeightMutArray removeAllObjects];
}
CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
[cellHeightMutArray insertObject:#(fittingSize.height) atIndex:webView.tag];
if (((webView.tag + 1) == dataArray.count) && !reloadedTableViewAfterLoadingWebContent) {
reloadedTableViewAfterLoadingWebContent = YES;
_tableView.hidden = NO;
[_tableView reloadData];
}
}
Then I adjust the height of the cell (which was the main issue that I had)
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (cellHeightMutArray.count > 0) {
return [[cellHeightMutArray objectAtIndex:indexPath.row] intValue];
}
return 44;
}
This is my solution and it works perfectly in iPhones and iPads.
But I had different issue when I run it with more complex user interface in iPads which is in my real project. I'll update this if my solutions for those issue related to this question.

UICollectionView Displays empty

Hi in my application in trying display the Flickr images in my UICollectionView but it shows a empty View Control
My code for display the Flickr images.
{
NSMutableArray *photoURLs;
NSMutableArray *photoSetNames;
NSMutableArray *photoids;
}
viewDidLoad code.
- (void)viewDidLoad
{
[super viewDidLoad];
photoURLs = [[NSMutableArray alloc] init];
photoSetNames = [[NSMutableArray alloc] init];
photoids = [[NSMutableArray alloc] init];
[self loadFlickrPhotos];
[self.collectionview reloadData];
}
- (void)loadFlickrPhotos {
NSString *urlString = [NSString stringWithFormat:#"https://www.flickr.com/services/rest/?method=flickr.photosets.getPhotos&format=json&api_key=a6a0c7d5efccffc285b0fe5ee1d938e3&photoset_id=72157644758906604&per_page=10&nojsoncallback=1",nil];
NSLog(#"the url string==%#",urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(#"the str==%#",jsonString);
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSArray *photosets = [[results objectForKey:#"photosets"] objectForKey:#"photoset"];
for (NSDictionary *photoset in photosets) {
NSString *title = [[photoset objectForKey:#"title"] objectForKey:#"_content"];
NSLog(#"title==%#",title);
[photoSetNames addObject:(title.length > 0 ? title : #"Untitled")];
NSString *primary = [photoset objectForKey:#"primary"];
NSString *server = [photoset objectForKey:#"server"];
NSString *secret = [photoset objectForKey:#"secret"];
NSString *farm = [photoset objectForKey:#"farm"];
NSString *urlstr=[NSString stringWithFormat:#"http://farm%#.staticflickr.com/%#/%#_%#.jpg",farm,server,primary,secret];
NSLog(#"your photo id==%#",urlstr);
[photoids addObject:urlstr];
}
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [photoids count];
}
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier =#"Cell";
imggpolitical *cell=(imggpolitical *) [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath: indexPath];
cell.imageview.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[photoids objectAtIndex:indexPath.row]]]]];
return cell;
}
I have used the above to display the Flickr images in UICollectionView but its coming as a empty view please tell me how to resolve this issue.
Thanks.
At the end of -(void)loadFlickrPhotos method, call reloadData on your UICollectionView. You need to tell UICollectionView to refresh its data.
Try [self.collectionview reloadData]
I don't see that you're assigning a delegate or data source. Or for that matter, created your UICollectionView.

iOS: how can I assign each of my cells a tag in this method?

I need to update each cell with a tag id. I have completed this, but there is one crucial flaw. When I change the order of the cells, the cells will inherit the wrong id.For example,if I swap cell 2 for cell 1 , cell 1 will get cell 2 id and cell 2 will get cell 1 id. Each ID needs to be for a specific cell and one cell only so that way if I changed the order the cell it will contain its id. I believe the issue is I am calling id in my UICollectionView delegate and so that way every time it updates it call from the server and reuses the id again. How can I get around this?
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
[self.collectionView registerClass:[Cell class] forCellWithReuseIdentifier:#"Cell"];
Cell *cell = (Cell*)[collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
if (self.data == nil || [self.data count] == 0) {
self.data = [sections objectAtIndex:indexPath.section];
cell.cellImg.image = nil;
[tagArray removeAllObjects];
} else {
self.data = [sections objectAtIndex:indexPath.section];
cell.cellImg.image = [self.data objectAtIndex:indexPath.item];
self.largeImage.image = [self.data objectAtIndex:0];
NSDictionary *url = [self.result objectAtIndex:indexPath.row];
NSString *string = [url valueForKey:#"id"];
cell.cellImg.tag = string.intValue;
[tagArray addObject:[NSNumber numberWithInt:cell.cellImg.tag]];
}
return cell;
}
-(void)didGetResults:(NSArray *)resultArray
{
self.resultArray = resultArray;
resultModel = [self.resultArray objectAtIndex:0];
self.resultdata = resultModel.resultdata;
sections = [[NSMutableArray alloc] initWithCapacity:SECTION_COUNT];
for(int s = 0; s < SECTION_COUNT; s++) {
self.data = [[NSMutableArray alloc] initWithCapacity:self.resultdata.count];
for(int i = 0; i < self.result.count; i++) {
NSDictionary *url = [self.result objectAtIndex:i];
NSString *string = [url valueForKey:#"web_path"];
UIImageView *myImageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:string]]]];
[self.data addObject:myImageView.image];
}
[sections addObject:self.data];
}
[tagArray removeAllObjects];
[self.collectionView reloadData];
}
What you can do is read the cell id first, and then see if that tag id matches an id in your list. If it doesn't, assign it an id (assuming first load of that particular cell or the whole table view in general). If it does, do not assign a new value. I know this method is not particularly safe if your assignable id values are in the range of the table view. In that case, use a hash or large numbered id or one that is a concatenation of filler ints like id[1] = 1001 and id[2] = 1002.

How to add a search bar and search display to an rss feed in UItableview

I created an RSS reader that parses from a .xml file. I am trying to create a search bar and search display controller, but am not sure how to search the objectForKey "title" or objectForKey "summary" within the UITableView.
Any help would be greatly appreciated.
The numberOfRowsInSection and cellForRowAtIndexPath looked like this:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.parseResults.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//Check if cell is nil. If it is create a new instance of it
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure titleLabel
cell.textLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"title"];
cell.textLabel.numberOfLines = 2;
//Configure detailTitleLabel
cell.detailTextLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"summary"];
cell.detailTextLabel.numberOfLines = 2;
//Set accessoryType
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//Set font and style
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
return cell;
}
I recently tried to follow this sample project - https://github.com/deepthit/TableViewSearch.git - based on a suggestion.
My code then looked like this:
#interface QldRecentJudgmentsViewController () {
__strong NSArray *mFilteredArray_;
__strong UISearchBar *mSearchBar_;
__strong UISearchDisplayController *mSearchDisplayController_;
}
#end
#implementation ViewController
#synthesize parseResults = _parseResults, HUD;
- (void)viewDidLoad {
[super viewDidLoad];
mSearchBar_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0,
0,
self.view.bounds.size.width,
44)];
mSearchBar_.delegate = self;
mSearchBar_.placeholder = #"search";
self.tableView.tableHeaderView = mSearchBar_;
mSearchDisplayController_ = [[UISearchDisplayController alloc] initWithSearchBar:mSearchBar_
contentsController:self];
mSearchDisplayController_.searchResultsDelegate = self;
mSearchDisplayController_.searchResultsDataSource = self;
mSearchDisplayController_.delegate = self;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
//return self.parseResults.count;
if (tableView == self.searchDisplayController.searchResultsTableView ||
[mFilteredArray_ count] > 0)
{
return [mFilteredArray_ count];
}
return parseResults.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
id result;
if (tableView == self.searchDisplayController.searchResultsTableView ||
[mFilteredArray_ count] > 0)
{
result = [mFilteredArray_ objectAtIndex:indexPath.row];
}
else
{
result = [parseResults objectAtIndex:indexPath.row];
}
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//Check if cell is nil. If it is create a new instance of it
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure titleLabel
cell.textLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"title"];
cell.textLabel.numberOfLines = 2;
//Configure detailTitleLabel
cell.detailTextLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"summary"];
cell.detailTextLabel.numberOfLines = 2;
//Set accessoryType
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//Set font and style
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *url = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"link"];
NSString *title = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"title"];
WebViewController *viewController = [[WebViewController alloc] initWithURL:url title:title];
[self.navigationController pushViewController:viewController animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar
textDidChange:(NSString *)searchText {
if ([searchText length] == 0)
{
[self.tableView reloadData];
return;
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.title contains[cd] %# OR SELF.summary contains[cd] %#", searchText, searchText];
mFilteredArray_ = [self.parseResults filteredArrayUsingPredicate:predicate];
[self.tableView reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
mFilteredArray_ = nil;
[self.tableView reloadData];
}
However, when I follow this the RSS feed does not load anymore in the tableview, so there are no results. Nevertheless when I try to search it does not correctly search the "title" or "summary" and the search results do not appear correctly -the cells are not neatly aligned after searching for something and getting results. Also, the only way to see RSS in the tableview is to search for any generic string, but once you press cancel in the search bar the RSS feed disappears and shows an empty tableview.
Thanks for any help in advance.

Loading data from cell to detailView always show the last data

I have UITableView with some data from backend, I have everything in table,3 UILable and I will get that information from backend and I can show them in table row, when I click on row I want to have the same label in my detail view, but now, I have just one information in all my detail view, same information, just load the last row for all detailView,
would you please help me in this implementation,
Thanks in advance!
cellForRowAtIndexPath method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath
{
static NSString *CellIdentifier = #"BooksCell";
BooksCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell =[ [[NSBundle mainBundle] loadNibNamed:#"BooksCell" owner:nil options:nil]
lastObject];
}
_books = [server get_tests:10 offset:0 sort_by:0 search_for:#""];
_t = [NSMutableString stringWithFormat:#"%# ", [_books objectAtIndex:indexPath.row]];
NSString *testdata = _t;
_components = [testdata componentsSeparatedByString:#","];
NSLog(#"_components: %#",_components);
for (NSString *aComponent in _components) {
if ([aComponent hasPrefix:#"title"]) {
_subComponents = [aComponent componentsSeparatedByString:#":"];
_titleString = [_subComponents[1] stringByTrimmingCharactersInSet:[NSCharacterSet
characterSetWithCharactersInString:#"\""]];
}if ([aComponent hasPrefix:#"authors"]){
_subComponents = [aComponent componentsSeparatedByString:#":"];
_writerString = [_subComponents[1] stringByTrimmingCharactersInSet:[NSCharacterSet
characterSetWithCharactersInString:#"\""]];
}if ([aComponent hasPrefix:#"name"]){
_subComponents = [aComponent componentsSeparatedByString:#":"];
_publisherString = [_subComponents[1] stringByTrimmingCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#"\""]];
break;
}
}
cell.bookTitle.text = _titleString;
cell.writer.text = _writerString;
cell.publisher.text = _publisherString;
return cell;
}
didSelectRowAtIndexPath method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath
*)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
BooksDetailView *c = [[BooksDetailView alloc] init];
[self.booksTable addSubview:c.view];
c.bDetailTitle.text = _titleString;
c.bDetailWriter.text = _writerString;
c.bDetailPublisher.text = _publisherString;
}
_titleString, _writerString and _publisherString seem to be instance variables
of the table view controller, and these are overwritten in cellForRowAtIndexPath
each time a cell is displayed.
You have to use the indexPath in didSelectRowAtIndexPath to get the correct element
of your data source.
Note also that fetching all elements from the server in cellForRowAtIndexPath
is very ineffective, because this method is called frequently.
You should fetch the data once (e.g. in viewDidLoad) and assign
the fetched array to an instance variable or property of the view controller.
Then you can access the elements from the array in cellForRowAtIndexPath and in
didSelectRowAtIndexPath.
Add a property
#property (strong, nonatomic) NSArray *books;
to the view controller. Fetch the data in viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
self.books = [server get_tests:10 offset:0 sort_by:0 search_for:#""];
// ... other stuff ...
}
In cellForRowAtIndexPath you just get the element from the array.
Also, instead of all that string manipulation, you should use the model class
and property accessors generated by the Thrift API.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath
{
static NSString *CellIdentifier = #"BooksCell";
BooksCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell =[[[NSBundle mainBundle] loadNibNamed:#"BooksCell" owner:nil options:nil] lastObject];
}
YourModelClass *book = self.books[indexPath.row];
cell.bookTitle.text = book.title;
// ...
return cell;
}
And similarly in didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath
*)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
BooksDetailView *c = [[BooksDetailView alloc] init];
[self.booksTable addSubview:c.view]; // WHY THAT?
YourModelClass *book = self.books[indexPath.row];
c.bDetailTitle.text = book.title;
// ...
}

Resources