2015-03-28 1 views
0

У меня есть PFQueryTableView с UISearchBar для поиска пользователей из моего класса пользователей на сервере Parse, но я никогда не получаю его работу. Вот мой код:Поиск в PFQueryTableView не работает

SearchViewController.h

#import <Parse/Parse.h> 
@interface PAWUserSearch1ViewController : PFQueryTableViewController 
@end 

SearchViewController.m

#import "SearchViewController.h" 
#import "PAWAppDelegate.h" 

@interface SearchViewController() <UIGestureRecognizerDelegate, UISearchBarDelegate, UISearchDisplayDelegate> 
@property (strong, nonatomic) IBOutlet UISearchBar *searchBar; 
@property (nonatomic, strong) UISearchDisplayController *searchController; 
@end 

@implementation SearchViewController 

- (id)initWithStyle:(UITableViewStyle)style { 
    self = [super initWithStyle:style]; 
    if (self) { 
     self.parseClassName = [PFUser parseClassName]; 
     self.pullToRefreshEnabled = NO; 
     self.paginationEnabled = YES; 
     self.objectsPerPage = self.objects.count; 
    } 
    return self; 
} 

- (PFQuery *)queryForTable { 
    NSLog(@"searchbar text --> %@", self.searchBar.text); 

    PFQuery *query = [PFUser query]; 
    if ([self.searchBar.text length]!=0) { 
     PFQuery *userQuery = [PFUser query]; 
     [userQuery whereKey:kPAWParseUsernameKey matchesRegex:self.searchBar.text modifiers:@"i"]; 
     [query whereKey:kPAWParseUserKey matchesKey:@"objectId" inQuery:userQuery]; 
    } else { 
     [query whereKeyExists:@"featuredNote"]; //show only users with location detailed 
    } 

    return query; 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 
    return 1; 
} 

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    NSLog(@"number of users --> %i", self.objects.count); 
    return self.objects.count; 
} 

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

    static NSString *identifier = @"reuseIdentifier"; 
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:identifier]; 

    if (!cell) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
            reuseIdentifier:identifier]; 
    } 

    // display user name 
    NSString *userNameWithLocation = [NSString stringWithFormat:@"@%@ -%@", [self.objects[indexPath.row] objectForKey:kPAWParseUsernameKey], [self.objects[indexPath.row] objectForKey:@"featuredNote"]]; 
    cell.textLabel.text = userNameWithLocation; 
    cell.textLabel.textColor = [UIColor darkGrayColor]; 

    return cell; 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    return 70.0; 
} 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    //set nav 
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Done", nil) style:UIBarButtonItemStylePlain target:self action:@selector(doneButtonPressed:)]; 

    self.pullToRefreshEnabled = NO; 

    // Hide the search bar until user scrolls up 
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)]; 
    self.tableView.tableHeaderView = self.searchBar; 
    self.searchBar.delegate = self; 

    self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar 
                  contentsController:self]; 
    self.searchController.searchResultsDataSource = self; 
    self.searchController.searchResultsDelegate = self; 
    self.searchController.delegate = self; 

    CGPoint offset = CGPointMake(0, self.searchBar.frame.size.height); 
    self.tableView.contentOffset = offset; 

    self.searchBar.placeholder = NSLocalizedString(@"Username", nil); 
} 

- (IBAction)doneButtonPressed:(id)sender { 
    [self.presentingViewController dismissModalViewControllerAnimated:YES]; 
} 

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

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { 
    NSLog(@"search pressed!!!!!!"); 
    [searchBar resignFirstResponder]; 
    //[self.tableView reloadData]; 
    [self loadObjects]; 
} 
@end 

Этот код отображает всех пользователей, если их "featuredNote" выходит - эта часть работает отлично, но когда я ищу, он не показывает результаты поиска. Я набираю ключевое слово в поле поиска, и когда я нажимаю поиск по клавиатуре, убирается метод searchBarSearchButtonClicked, но это все. Я ожидаю, что будет вызвано queryForTable, но это не так. В результате таблица по-прежнему показывает, что все пользователи являются оригинальными. Что я сделал не так, или я что-то пропустил? Пожалуйста, помогите. Огромное спасибо.

Обновление

Так как я заменил [self.tableView reloadData]; с [self loadObjects]; и я могу позвонить queryForTable после searchBarSearchButtonClicked. Однако, tableView numberOfRowsInSection все еще всегда возвращает ноль.

ответ

0

Вот код you asked for из проекта с подобной необходимостью реализации. Я закончил использование UISearchBar с отдельным UITableView, чтобы отобразить результаты. Обязательно создавайте правильные соединения раскадровки для UISearchBar и UITableView при их внедрении. Кроме того, панель поиска delegate должна быть установлена ​​на ViewController, а и dataSource должны быть установлены на ViewController.

static NSString * const kSearchResultsTableCellReuseIdentifier = @"SearchResultsTableCellReuseIdentifier"; 

@interface ViewController() 
    @property (nonatomic, strong) NSArray *searchResults; 
    @property (nonatomic, weak) IBOutlet UISearchBar *searchBar; 
    @property (nonatomic, weak) IBOutlet UITableView *searchResultsTable; 
@end 

@implementation ViewController 

... 

#pragma mark - Protocol conformance 

#pragma mark UISearchBarDelegate methods 

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 
{ 
    if([searchText length] == 0) 
    { 
     [self dismissSearch]; 
    } 
    else 
    { 
     [self handleSearchForString:searchText]; 
    } 
} 

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar 
{ 
    // any logic related to Search button being clicked 
} 

#pragma mark UITableViewDataSource methods 

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

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

    if (!cell) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kSearchResultsTableCellReuseIdentifier]; 
    } 

    // Search result text to be displayed in table 
    cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row].name; 

    return cell; 
} 

#pragma mark UITableViewDelegate methods 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // any logic for when a cell in the search results table is selected 

    [self dismissSearch]; 
}  

#pragma mark - Helpers 

- (void)handleSearchForString:(NSString *)searchString 
{ 
    // any logic for retrieving search results as an NSArray we'll call `results` 

    self.searchResults = results; 
    [self.searchResultsTable reloadData]; 

} 

- (void)dismissSearch 
{ 
    self.searchBar.text = @""; 

    [self.searchBar performSelector: @selector(resignFirstResponder) 
         withObject: nil 
         afterDelay: 0.1]; 
} 

@end 

Надежда, что помогает

1

Вы устанавливаете запрос, но вы не говорите это, чтобы сделать поиск, что вам нужно сделать что-то вроде этого:

[query whereKeyExists:@"featuredNote"];//this sets the query 

[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { 

    //Your code here 


}];//this PERFORMS the query 
+0

ты прав, так что я реализован код для поиска в блоке запроса, как вы предложили, но есть проблема. Как только я нахожу поиск, он показывает ошибку ** «Этот запрос имеет выдающееся сетевое соединение. Вы должны подождать, пока это не закончится ». ** Но спасибо, что указали это. – SanitLee

+0

Почему у вас есть два вопроса? PFQuery * query = [Запрос PFUser]; и PFQuery * userQuery = [запрос PFUser] ?. userQuery никогда не используется в этом коде. почему он там? – Kex

+0

можете ли вы разместить больше своего кода? если вы получаете эту ошибку, скорее всего, вы пытаетесь выполнить более одной операции на одном и том же объекте Parse одновременно. – Kex

Смежные вопросы