joshg47
joshg47

Reputation: 135

UITableView cellForRowAtIndexPath is not being called

I am having a problem with blank table data as this method is not getting called after I press search in my UISearchBar. I have tried everything and the table is just showing up blanking after pressing search. This code takes the description from my json url and scans it for the searched word and then puts the index location of whatever description has that search term into an array (self.indexArray). I would like to the call the table to only display those cells of the index values in that array.

- (void)viewDidLoad
{
    [super viewDidLoad];

    UISearchBar *tempSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, 320, 40)];
    self.searchBar = tempSearchBar;
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"Search listings...";

    [self.view addSubview:self.searchBar];

}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    [self sendData];
}

- (void)sendData
{
    NSString *search = self.searchBar.text;
    NSString *temp = [NSString stringWithFormat:@"MY JSON RETRIEVAL LINK"];
    NSURL *url = [[NSURL alloc] initWithString:temp];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
                                     initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation
                                           , id responseObject) {
        NSLog(@"%@",responseObject);
        NSLog(@"%@",[responseObject class]);
        self.images = responseObject;
        self.descriptions = [[NSMutableArray alloc] init];
        for (int i = 0; i < [self.images count]; i++)
        {
            [self.descriptions addObject:self.images[i][@"description"]];
        }
        for (int i = 0; i < [self.descriptions count]; i++)
        {
            NSLog(@"%d: %@", i, self.descriptions[i]);
            if ([self.descriptions[i] rangeOfString:search options:NSCaseInsensitiveSearch].location != NSNotFound)
            {
                NSLog(@"ADDING, %d", i);
                [self.indexArray addObject:[NSNumber numberWithInt:i]];
            }
        }
        tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,104,320,480) style:UITableViewStylePlain];
        tableView.dataSource = self;
        tableView.delegate = self;

        [self.view addSubview:tableView];
        [tableView reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error.localizedDescription);
    }];

    [operation start];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"FUNCTION CALLED");
    TLCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];

    if(cell == nil) {
        cell = [[TLCustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
    }

    for(UIView *view in cell.contentView.subviews){
        if ([view isKindOfClass:[UIView class]]) {
            [view removeFromSuperview];
        }
    }

    NSString *name = self.images[indexPath.row][@"name"];
    NSString *location = self.images[indexPath.row][@"location"];
    NSString *body = self.images[indexPath.row][@"description"];
    NSString *list_type = self.images[indexPath.row][@"category"];
    NSString *millisecs = self.images[indexPath.row][@"_createdAt"];

    NSDate *date = [NSDate date];
    NSTimeInterval ti = [date timeIntervalSince1970];
    double myDouble = [millisecs doubleValue];
    double delta = (ti * 1000) - myDouble;
    NSString *time = [self calculateInterval:delta];

    cell.nameLabel.text = name;
    cell.locationLabel.text = location;
    cell.bodyLabel.text = body;

    CGFloat fixedWidth = cell.bodyLabel.frame.size.width;
    CGSize newSize = [cell.bodyLabel sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = cell.bodyLabel.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    cell.bodyLabel.frame = newFrame;

    cell.timeLabel.text = time;

    if ([list_type isEqualToString:@"Sell"])
    {
        UIImageView *thumbnailView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sell_icon_small.png"]];
        thumbnailView.frame = CGRectMake(12, 12, 50., 50.);
        [cell addSubview:thumbnailView];
    }
    else if ([list_type isEqualToString:@"Trade"])
    {
        UIImageView *thumbnailView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"trade_icon_small.png"]];
        thumbnailView.frame = CGRectMake(12, 12, 50., 50.);
        [cell addSubview:thumbnailView];
    }
    else if ([list_type isEqualToString:@"Wanted"])
    {
        UIImageView *thumbnailView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"want_icon_small.png"]];
        thumbnailView.frame = CGRectMake(12, 12, 50., 50.);
        [cell addSubview:thumbnailView];
    }
    else
    {
        UIImageView *thumbnailView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ad_icon_small.png"]];
        thumbnailView.frame = CGRectMake(12, 12, 50., 50.);
        [cell addSubview:thumbnailView];
    }

    NSString *temp = self.images[indexPath.row][@"link"];
    if ([temp isEqualToString:@"no_link"])
    {
        _thereIsAnImage = FALSE;
    }
    else
    {
        _thereIsAnImage = TRUE;
    }

    if (_thereIsAnImage)
    {

        SDWebImageManager *manager = [SDWebImageManager sharedManager];
        [manager downloadWithURL:self.images[indexPath.row][@"link"]
                     options:0
                        progress:^(NSInteger receivedSize, NSInteger expectedSize)
         {
             // progression tracking code
         }
                       completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished)
         {
             if (image)
             {

                 cell.imageView.image = image;

                 cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
                 cell.imageView.clipsToBounds = YES;
                 cell.imageView.tag = indexPath.row;


                 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap:)];
                 [tap setNumberOfTapsRequired:1];
                 [tap setNumberOfTouchesRequired:1];
                 [cell.imageView setUserInteractionEnabled:YES];
                 [cell.imageView addGestureRecognizer:tap];

             }
         }];
    }

    return cell;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.indexArray.count;
}

Upvotes: 1

Views: 2518

Answers (5)

andrewbuilder
andrewbuilder

Reputation: 3791

I would ask that you please check your header file - it should include the following...

@interface YourTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate>

Investigate how to implement UISearchBarDelegate and UISearchDisplayDelegate methods to manage search function in your (table) view controller. Read the Apple documentation UISearchBarDelegate and UISearchDisplayDelegate.

When you use a UISearchBar, you need a UISearchDisplayController to manage the search results.

If you are not using storyboards, it is important to set the appropriate data source and delegates for instances of both the UITableView and the UISearchDisplayController in your UITableViewController.

Then in your two table view data source methods, you need to provide information to the searchResultsTableView (accessed via self.searchDisplayController.searchResultsTableView) so that it knows how to prepare the search results table view.

For example...

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger nofRowsInSection = 0;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        nofRowsInSection = self.searchResults.count;
    } else {
        nofRowsInSection = self.indexArray.count;
    }
    return nofRowsInSection;
}

...and...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ... <<other code>> ...

    NSString *name = nil;
    NSString *location = nil;
    etc...

    if (tableView == self.searchDisplayController.searchResultsTableView) {
            name = self.searchResults[indexPath.row][@"name"];
            location = self.searchResults[indexPath.row][@"location"];
            ...etc...

    } else {
            name = self.images[indexPath.row][@"name"];
            location = self.images[indexPath.row][@"location"];
            ...etc...

    }

    ... <<other code>> ...
}

Note that self.searchResults should be an NSMutableArray and it should contain data for the search results table view, prepared by filtering self.indexArray based on the search bar text.

Hope this helps.

Upvotes: 0

ashForIos
ashForIos

Reputation: 399

If you are doing it programmatically then you need to set tableview.delegate = self and tableview.datasource = self in viewDidLoad method. Put a breakpoint in numberOfRowsInSection: to see the number that it's returning to check whether it's more than zero or not.

Upvotes: 2

lukas
lukas

Reputation: 2410

You need to set tableView.delegate = self and tableView.dataSource = self in the viewDidLoad

Upvotes: 0

JWKot
JWKot

Reputation: 360

Did you put

@interface YourViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

to the top of you ViewController.m file?

Upvotes: 0

Macrosoft-Dev
Macrosoft-Dev

Reputation: 2185

Your code seems OK . check whether table from storeybaord is connected with the table and delegated correctly.

Upvotes: 0

Related Questions