Xcode 使用UISearchBar调用API

Xcode 使用UISearchBar调用API,xcode,api,uisearchbar,uisearchdisplaycontroller,Xcode,Api,Uisearchbar,Uisearchdisplaycontroller,我有一个显示API结果的UITableView。只要用户通过searchBar:textDidChange:键入UISearchBar,就会调用API。有效地实现自动完成搜索。我的问题是加载到UITableView中的结果似乎是上次API调用之后的一次迭代 例如: 用户在UISearchBar中键入“union”,但UITableView中不会显示任何结果。用户在“union”、“unions”之后键入任何字符,例如,“union”的API结果将显示在UITableView中。当用户向下滚动浏览

我有一个显示API结果的UITableView。只要用户通过searchBar:textDidChange:键入UISearchBar,就会调用API。有效地实现自动完成搜索。我的问题是加载到UITableView中的结果似乎是上次API调用之后的一次迭代

例如: 用户在UISearchBar中键入“union”,但UITableView中不会显示任何结果。用户在“union”、“unions”之后键入任何字符,例如,“union”的API结果将显示在UITableView中。当用户向下滚动浏览(联合,但实际上是“联合”)结果时,“重新填充的单元格”显示“联合”结果

SearchViewController.h

#import <UIKit/UIKit.h>

@interface SearchViewController : UIViewController <UITextFieldDelegate, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, UISearchDisplayDelegate>{
    UITableView *searchTableView;
    UISearchBar *sBar;
    UISearchDisplayController *searchDisplayController;
}

@property (strong, nonatomic) NSArray *loadedSearches;

@end
如果我的问题不清楚,请告诉我

请随意评论代码的其他方面,但是我真的很感激我的问题的解决方案:)提前谢谢


示例API响应-

您的请求是异步工作的,它可能与scroll或其他内容无关。此时返回的只是结果。尝试取消以前的请求。例如,如果您尝试搜索“联合”,则取消“联合”请求。希望有帮助。

问题似乎是,在使用AFJSONRequestOperation进行异步操作时,在获取数据之前正在刷新表。因此,您的模型可能得到了正确的更新,但是您的tableview落后了一次刷新。尝试在块成功回调中移动[searchTableView reloadData]:

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
      success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
      {
          self.loadedSearches = JSON[@"response"][@"venues"];

          // refreshing the TableView when the block gets the response
          [searchTableView reloadData];
      }
      failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
      {
          NSLog(@"%@", error.localizedDescription);
      }];
希望这能奏效

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
      success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
      {
          self.loadedSearches = JSON[@"response"][@"venues"];

          // refreshing the TableView when the block gets the response
          [searchTableView reloadData];
      }
      failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
      {
          NSLog(@"%@", error.localizedDescription);
      }];