Search code examples
iosuitableviewnsnotification

reload tableView in last method run


I have method that get notification as I download one image. I can download a lot of objects and I want to update tableView then I have last notification of downloaded image. How the best way to accomplish it?

- (void)requestDownloadAvatarWithImageString:(NSString *)imageString completion:(void (^)(AFHTTPRequestOperation *operation, UIImage *image, NSError *error))completion __attribute__((nonnull(2)))
{
NSParameterAssert(completion);

NSString *urlString = imageString;
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
requestOperation.responseSerializer = [AFImageResponseSerializer serializer];

[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    completion(operation, responseObject, nil);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    DDLogError(@"FAIL download image: %@",error);
}];

[requestOperation start];
}

Solution

  • dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(NUMBER_OF_RETURNED_OBJECTS);
    dispatch_async(queue, ^{
        for (i = 0; i<NUMBER_OF_RETURNED_OBJECTS; i++)
        {
            dispatch_async(queue, ^{
    
                fetchObject(i); // it's specific to your application
    
                dispatch_semaphore_signal(semaphore);
            }
        }
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    }   
    
    [your_table_view reloadData];
    

    or simply get all image paths in an array then download them with SDWebImage

    - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    
    
    NSString *url = [NSString stringWithString, imageArray[indexPath.row]];
    
    [cell.cell_image setImageWithURL:[NSURL URLWithString: url] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    
    }