我正在尝试在我的应用程序中实现搜索功能,在用户点击键盘上搜索后,HTTP
请求将被发送到API,返回的数据将显示在我的UITableView
中。但是,它不起作用,我认为是因为请求在一个单独的线程中运行。我尝试了一堆不同的解决方案,但似乎都没有。以下是我的代码。谢谢您的帮助!
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
//get string from searchBar textfield
NSString* searched = self.searchBar.text;
//format the API call to search for the "searched" item (%@ after 'search/')
NSString* formattedURL = [NSString stringWithFormat:@"https://api.nutritionix.com/v1_1/search/%@?results=0:100&fields=item_name,nf_total_fat,nf_protein,nf_total_carbohydrate&appId=f35a80a7&appKey=9263d4b1c216becb04681b1cd04d1815",searched];
dispatch_async(dispatch_get_main_queue(), ^{
[[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:formattedURL] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary* foodsFoundDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//array holds an array of all the foods found from the API call
NSArray* array;
array = [foodsFoundDict valueForKey:@"hits"];
//since the info needed is inside the dictionary @"fields" of each array element, loop through array and add each dictionary to the global searchedFoodsArray
for(NSDictionary* dict in array){
[self.searchedFoodsArray addObject:dict[@"fields"]];
}
}]resume];
[self.tableView reloadData];
});
}
您的问题似乎是您在URL请求的完成块之外重新加载数据。另外,我再看看你在主队列上放置任务的位置。
我认为问题是你正在围绕后台进程包裹主队列(NSURLSession调用)。 NSURLSession实际上是在后台运行。因此,您需要在NSURLSession块中包含主队列GCD。例如:
[[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:formattedURL] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// your code updating tableview datasource.
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}]resume];
只需添加到您的关闭:
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
如果您希望搜索结果以被动方式更新。为搜索结果创建一个单独的数组,并通过检查qazxsw poi更新您的表视图以使用该数组