I am working on a product application where user could sell/buy. This application is based on collection view. Collection view has collection cell where it displays product image thumbnail.

The following code gets products images from the server and it waits to download all images and then display them in the cells. The following code works but the user should wait 20-40 seconds to see products.

I highly suspect this implementation architecture is not good.

- (void)viewDidLoad {
    [super viewDidLoad];
     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
     dispatch_async(queue, ^(void) {
        [self loadFromURL];
     dispatch_async(dispatch_get_main_queue(), ^{

-(void)loadFromURL {
    NSURL *url = [NSURL URLWithString:@"http://myURL/productAll.php"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

   [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) 
      pElements= (NSMutableArray *)responseObject;
      [collectionView reloadData];

     failure:^(AFHTTPRequestOperation *operation, NSError *error) 
       UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Product" message:[error localizedDescription]delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
     [alertView show];
  [operation start];

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
    return pElements.count;

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    ProductCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    cell.backgroundColor=[UIColor whiteColor];
    NSString *arrayResult = [[pElements objectAtIndex:indexPath.row] objectForKey:@"image"];
    NSData *data = [[NSData alloc] initWithBase64EncodedString:arrayResult options:NSDataBase64DecodingIgnoreUnknownCharacters];
    cell.productImage.image = [[UIImage alloc] initWithData:data];
    cell.productImage.layer.cornerRadius = 10;
    cell.productImage.clipsToBounds = YES;
    return cell;
  • \$\begingroup\$ How many images does productAll.php usually return? How many images are displayed to the user on one screen? In other words are all of the images returned shown on one screen, or are some off screen waiting for the user to scroll/page to them? \$\endgroup\$ – dstudeba Nov 4 '15 at 18:50
  • 1
    \$\begingroup\$ Why do you have an empty dispatch_async to main thread? \$\endgroup\$ – nhgrif Nov 22 '15 at 16:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.