在将第二个字母键入搜索栏后,TableView没有显示任何内容

时间:2015-03-12 08:38:16

标签: ios uitableview uisearchbar

我使用json解析并设法从网站获取信息并在表视图中显示它。我设法设置搜索栏,以便搜索文本。但是,当我输入我的第二个字母时,表格视图中没有任何内容,即使有两个字母开头的单词。我在下面添加了我的代码。

@implementation EventsTableViewController
@synthesize searchBar, filteredEventsArray, eventNamesArray, isFiltered, eventsDictionary;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.eventNamesArray = [NSMutableArray array];
    self.eventsDictionary = [NSMutableDictionary dictionary];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self searchForEvents];
}

//Json Parsing
- (void)searchForEvents
{


    NSString *eventsSearchUrlString = [NSString stringWithFormat:@"https://www.googleapis.com/blogger/v3/blogs/1562818803553764290/posts?key=AIzaSyBTOxz-vPHgzIkw9k88hDKd99ILTaXTt0Y"];
    NSURL *eventsSearchUrl = [NSURL URLWithString:eventsSearchUrlString];
    NSURLRequest *eventsSearchUrlRequest = [NSURLRequest requestWithURL:eventsSearchUrl];

    NSURLSession *sharedUrlSession = [NSURLSession sharedSession];
    NSURLSessionDataTask *searchEventsTask =
    [sharedUrlSession dataTaskWithRequest:eventsSearchUrlRequest completionHandler:
     ^(NSData *data, NSURLResponse *response, NSError *error)
     {
         dispatch_async(dispatch_get_main_queue(),
                        ^{
                            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

                            if(error)
                            {
                                UIAlertView *searchAlertView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Please check your internet connection" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                                [searchAlertView show];
                            }
                            else
                            {
                                NSString *resultString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                NSLog(@"Search results: %@", resultString);

                                NSError *jsonParseError = nil;
                                NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParseError];

                                if(jsonParseError)
                                {
                                    UIAlertView *jsonParseErrorAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:jsonParseError.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                                    [jsonParseErrorAlert show];
                                }
                                else
                                {
                                    for(NSString *key in jsonDictionary.keyEnumerator)
                                    {
                                        NSLog(@"First level key: %@", key);
                                    }

                                    [self.eventNamesArray removeAllObjects];
                                    [self.eventsDictionary removeAllObjects];

                                    NSArray *searchResultsArray = [jsonDictionary objectForKey:@"items"];
                                    //NSLog(@"test%@",searchResultsArray);


                                    for(NSDictionary *eventsInfoDictionary in searchResultsArray)
                                    {
                                        Events *event = [[Events alloc] init];
                                        event.eventName = [eventsInfoDictionary objectForKey:@"title"];
                                        event.eventDescription =[eventsInfoDictionary objectForKey:@"content"];

                                        NSLog(@"Event Name : %@",event.eventName);
                                        NSLog(@"Event Description : %@",event.eventDescription);

                                        NSString *eventsAsStrings = [event.eventName substringToIndex:1];
                                        NSMutableArray *eventsInArray = [self.eventsDictionary objectForKey:eventsAsStrings];

                                        if(!eventsInArray)
                                        {
                                            eventsInArray = [NSMutableArray array];
                                            [self.eventNamesArray addObject:eventsAsStrings];
                                        }

                                        [eventsInArray addObject:event];

                                        [self.eventsDictionary setObject:eventsInArray forKey:eventsAsStrings];

                                        if ([event.eventDescription containsString:@"<br />"]) {
                                            NSString* eventDescrip = event.eventDescription;
                                            NSString* stringWithoutHTMLtags = [eventDescrip stringByReplacingOccurrencesOfString:@"<br />" withString:@""];
                                            event.eventDescription = stringWithoutHTMLtags;
                                        }
                                        NSLog(@"Event Name : %@",event.eventName);
                                        NSLog(@"Event Description : %@",event.eventDescription);

                                    }

                                    [self.eventNamesArray sortedArrayUsingComparator:^NSComparisonResult(Events *obj1, Events *obj2) {
                                        Events *time1 = obj1;
                                        Events *time2 = obj2;
                                        if (time1 > time2) {
                                            return (NSComparisonResult)NSOrderedDescending;
                                        }
                                        else if (time1 < time2) {
                                            return (NSComparisonResult)NSOrderedAscending;
                                        }
                                        return (NSComparisonResult)NSOrderedSame;
                                    }];
                                    [self.tableView reloadData];
                                }
                            }
                        });
     }];

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [searchEventsTask resume];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchText.length == 0) {
        isFiltered = NO;
    }
    else {
        isFiltered = YES;
    }
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",searchText];
    self.filteredEventsArray = [eventNamesArray filteredArrayUsingPredicate:pred];
    [self.tableView reloadData];
}

//- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
 //   [resign fi]
//}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (isFiltered == YES) {
        return filteredEventsArray.count;
    }
    else {
        return self.eventNamesArray.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *eventsWithFirstLetter;
    if (isFiltered == YES) {
        NSString *firstLetter = [self.filteredEventsArray objectAtIndex:section];
        eventsWithFirstLetter = [self.eventsDictionary objectForKey:firstLetter];
        return eventsWithFirstLetter.count;
    }
    else {
        NSString *firstLetter = [self.eventNamesArray objectAtIndex:section];
        eventsWithFirstLetter = [self.eventsDictionary objectForKey:firstLetter];
        return eventsWithFirstLetter.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"eventTitleCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    Events *event;
    if (isFiltered == YES) {
        NSString *firstLetter = [self.filteredEventsArray objectAtIndex:indexPath.section];
        NSArray *eventsWithFirstLetter = [self.eventsDictionary objectForKey:firstLetter];
        event = [eventsWithFirstLetter objectAtIndex:indexPath.row];
        cell.textLabel.text = event.eventName;
    }
    else {
        NSString *firstLetter = [self.eventNamesArray objectAtIndex:indexPath.section];
        NSArray *eventsWithFirstLetter = [self.eventsDictionary objectForKey:firstLetter];
        event = [eventsWithFirstLetter objectAtIndex:indexPath.row];
        cell.textLabel.text = event.eventName;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *firstLetter = [self.eventNamesArray objectAtIndex:indexPath.section];
    NSArray *eventsWithFirstLetter = [self.eventsDictionary objectForKey:firstLetter];
    Events *event = [eventsWithFirstLetter objectAtIndex:indexPath.row];

    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
    DescriptionViewController *descriptionViewController = (DescriptionViewController*)[mainStoryboard instantiateViewControllerWithIdentifier: @"descriptionController"];
    descriptionViewController.eventNameDesc = event.eventDescription;
    descriptionViewController.navigationItem.title = event.eventName;
    [self.navigationController pushViewController:descriptionViewController animated:YES];

}



@end

1 个答案:

答案 0 :(得分:1)

如果我读得正确,您只能在eventNamesArray NSString *eventsAsStrings = [event.eventName substringToIndex:1];中存储一个字母。

因此,如果您输入一个字母,谓词self.filteredEventsArray = [eventNamesArray filteredArrayUsingPredicate:pred];将只匹配。

因此,一个简单的解决方案是将完整的事件名称存储在自己的数组中,以便您可以匹配这些名称。