使用UISearchController搜索TableView时,只显示标题作为结果,而不是附带的图像和网址

时间:2015-12-15 18:10:20

标签: ios objective-c json uitableview uisearchcontroller

我有一个包含项目列表的表格。每个单元格都有项目标题,背景图像和单击单元格时打开的URL。

我有一个工作搜索功能,可以搜索标题,并使用符合搜索条件的项目更新它创建的表格。不幸的是,只有标题显示在searchResults表视图中,并且单击更新的单元格时没有任何反应。我不知道如何为细胞或网址显示附带的图像。

我认为问题是因为我只搜索标题并填充searchResults数组,该数组构成了搜索标题的searchResults表的内容,这忽略了附带的图像和网址。我不确定如何通过搜索标题来包含标题,图片和网址。

信息来自json,格式为:

{
    "items":
        [
            {
                "title":"title1",
                "url":"url1",
                "thumbnail":"thumbnailURL1"
            },

            {
                "title":"title2",
                "url":"url2",
                "thumbnail":"thumbnailURL2"
            }
        ]
}

我的其余代码如下所示:

WikiViewController.m(要搜索的表)

#import "WikiViewController.h"
#import "NavigationViewController.h"
#import "WebViewController.h"
#import "WikiSearchResultsViewController.h"


@interface WikiViewController () <NSURLSessionDataDelegate, UISearchResultsUpdating, UISearchControllerDelegate>

@property (nonatomic) NSURLSession *session;
@property (nonatomic, copy) NSArray *jsonArray;

@property (strong, nonatomic) UISearchController *controller;
@property (strong, nonatomic) NSArray *results;

@end


@implementation WikiViewController


#pragma mark - viewDid...

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.tableView registerClass:[UITableViewCell class]
           forCellReuseIdentifier:@"UITableViewCell" ];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchButtonPressed:)];


    WikiSearchResultsViewController *searchResults = (WikiSearchResultsViewController *)self.controller.searchResultsController;
    [self addObserver:searchResults forKeyPath:@"results" options:NSKeyValueObservingOptionNew context:nil];

}

# pragma mark - Search Results Updater


- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {

    // filter the search results
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [cd] %@", self.controller.searchBar.text];
    self.results = [[self.jsonArray valueForKey:@"title"] filteredArrayUsingPredicate:predicate];

}

- (void)searchButtonPressed:(id)sender {

    // present the search controller
    [self presentViewController:self.controller animated:YES completion:nil];

}

- (UISearchController *)controller {

    if (!_controller) {

        // instantiate search results table view
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Wiki" bundle:nil];
        WikiSearchResultsViewController *resultsController = [storyboard instantiateViewControllerWithIdentifier:@"SearchResults"];

        // create search controller
        _controller = [[UISearchController alloc]initWithSearchResultsController:resultsController];
        _controller.searchResultsUpdater = self;

        // optional: set the search controller delegate
        _controller.delegate = self;

    }
    return _controller;
}



#pragma mark - Table View

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.jsonArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"
                                                            forIndexPath:indexPath];

    NSDictionary *item = self.jsonArray[indexPath.row];

    if (![item[@"thumbnail"] isKindOfClass:[NSNull class]]) {
        NSString *urlString = [[NSString alloc] initWithString:item[@"thumbnail"]];
        NSURL *url = [NSURL URLWithString:urlString];
        NSData * imageData = [[NSData alloc] initWithContentsOfURL: url];
        UIImageView *bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:imageData]];

        [bgImageView setContentMode:UIViewContentModeScaleAspectFill];
        [bgImageView setClipsToBounds:YES];

        cell.backgroundView = bgImageView;
    }

    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.text = item[@"title"];


    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WebViewController *webViewController = [[WebViewController alloc] init];

    NSDictionary *item = self.jsonArray[indexPath.row];
    NSURL *baseURL = [NSURL URLWithString:@"http://www.baseurl.com"];
    NSURL *URL = [NSURL URLWithString:item[@"url"] relativeToURL:baseURL];

    webViewController.URL = URL;
    [self.navigationController pushViewController:webViewController
                                         animated:YES];
}


#pragma mark - Creating NSURLSession

- (instancetype)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {

        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:config
                                                 delegate:self
                                            delegateQueue:nil];
        [self fetchFeed];
    }
    return self;
}


- (void)fetchFeed
{
    NSString *requestString = @"http://www.requeststring.com";
    NSURL *url = [NSURL URLWithString:requestString];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];

    NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req
                                                     completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                         NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
                                                                                                                    options:0
                                                                                                                      error:nil];
                                                         self.jsonArray = jsonObject[@"items"];

                                                         NSLog(@"%@", self.jsonArray);

                                                         dispatch_async(dispatch_get_main_queue(), ^{[self.tableView reloadData];
                                                         });
                                                     }];
    [dataTask resume];
}

@end

WikiSearchResultsViewController.m(搜索结果表视图)

#import "WikiSearchResultsViewController.h"
#import "WikiViewController.h"
#import "WebViewController.h"

@interface WikiSearchResultsViewController () <NSURLSessionDataDelegate, UITableViewDataSource, UITableViewDelegate, UISearchControllerDelegate>

@property (nonatomic, strong) NSArray *searchResults;

@property (nonatomic) NSURLSession *session;
@property (nonatomic, copy) NSArray *jsonArray;

@end


@implementation WikiSearchResultsViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    _session = [NSURLSession sessionWithConfiguration:config
                                             delegate:self
                                        delegateQueue:nil];

    [self fetchFeed];
}

#pragma mark - Table view data source

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

    return self.searchResults.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];

    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];
    cell.textLabel.textColor = [UIColor blackColor];

    return cell;
}

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


    WebViewController *webViewController = [[WebViewController alloc] init];

    for (NSDictionary *item in _jsonArray){
        NSURL *baseURL = [NSURL URLWithString:@"http://www.baseurl.com"];
        NSURL *URL = [NSURL URLWithString:item[@"url"] relativeToURL:baseURL];

        webViewController.title = [self.searchResults objectAtIndex:indexPath.row];
        webViewController.URL = URL;
        [self.navigationController pushViewController:webViewController
                                             animated:YES];
    }



}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {

    // extract array from observer
    self.searchResults = [(NSArray *)object valueForKey:@"results"];
    [self.tableView reloadData];
}



#pragma mark - Creating NSURLSession

- (void)fetchFeed
{
    NSString *requestString = @"http://www.requeststring.com";
    NSURL *url = [NSURL URLWithString:requestString];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];

    NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req
                                                     completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                         NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
                                                                                                                    options:0
                                                                                                                      error:nil];
                                                         self.jsonArray = jsonObject[@"items"];

                                                         NSLog(@"%@", self.jsonArray);

                                                         dispatch_async(dispatch_get_main_queue(), ^{[self.tableView reloadData];
                                                         });
                                                     }];
    [dataTask resume];
}


@end

0 个答案:

没有答案