简体   繁体   English

UITableView不会在HTTP请求后重新加载数据

[英]UITableView doesn't reload data after HTTP request

I'm trying to implement a search function in my application where after the user taps search on the keyboard an HTTP request will be sent to the API and the data returned will be displayed in my UITableView . 我正在尝试在我的应用程序中实现搜索功能,其中在用户点击键盘上的搜索后, HTTP请求将发送到API,返回的数据将显示在UITableView However, it's not working and I think it because the request is running in a separate thread. 但是,它不起作用,我认为是因为请求在单独的线程中运行。 I've tried a bunch of different solutions but none seem to work. 我尝试了很多不同的解决方案,但似乎都没有用。 Below is my code. 下面是我的代码。 Thanks for the help! 谢谢您的帮助!

-(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];

    });

}

Your problem appears to be that you're reloadData'ing the tableView outside of the completion block of the URL request. 您的问题似乎是您要在URL请求的完成块之外对tableView重新加载数据。 In addition, I'd take a second look at where you're putting tasks on the main queue. 另外,我还要再看一遍将任务放置在主队列中的位置。

I think the problem is you are wrapping main queue grabbing around the background process (NSURLSession call). 我认为问题在于您正在围绕后台进程(NSURLSession调用)包装主队列。 NSURLSession is actually running in background. NSURLSession实际上在后台运行。 So you need to have the main queue GCD inside the NSURLSession block. 因此,您需要在NSURLSession块中包含主队列GCD。 For example: 例如:

    [[[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];

Simply Add to your closure: 只需添加到您的封闭:

dispatch_async(dispatch_get_main_queue(), ^{

           [self.tableView reloadData];
});

If you want your search Results to update in a reactive manner. 如果您希望搜索结果以被动方式更新。 create a seperate array for Search Result and update your table view to use that array by checking self.searchBar.isActive 为搜索结果创建一个单独的数组,并通过检查self.searchBar.isActive更新表视图以使用该数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM