0

ブログから情報を取得するアプリを作成しました。情報を正常に取得してテーブルビューに表示できます。次に、検索バーと検索表示コントローラーを作成して、情報を検索できるようにしました。実行すると、エラーは発生せず、情報が取得されて表示されます。しかし、検索バーに文字を入力すると、その文字から始まる単語があるにもかかわらず、テーブルビューにセルがありません。

これは私の.mファイルのコードです

@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;
    }
    for (NSString *eventName in eventNamesArray) {
        NSRange eventNameRange = [eventName rangeOfString:searchText options:NSCaseInsensitiveSearch];
        if (eventNameRange.location != NSNotFound) {
            [filteredEventsArray addObject:eventName];
        }
    }
    [self.tableView reloadData];
}

#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
4

0 に答える 0