Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling web services with asynchImageView

I am having a problem in calling web services when the image are being loaded in the tableView with AsynchImageView files .

Below are the steps of my problem:

  1. I call the web service and when it returns the data i reload the UITableView and load all images with AsynchImageView . The web service returns url of images and some text data .
  2. While the images are being loaded , if I call the same web service again then it runs for 30 seconds and then it times out without returning anything but after that time it works fine whenever I call it .

Here is my code for calling services:

-(void)getUserNotificationsPage:(int)page CallBack:(getNotifications)callback{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^ {
       @try {

            getNotificationsArrayResponseCallback=callback;


            NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?token=%@&page=%@",GET_USER_NOTIFICATIONS,[[NSUserDefaults standardUserDefaults]objectForKey:@"token"],[NSString stringWithFormat:@"%i",page]]]];


            NSError *err;
            NSData *returnData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&err];
            if(err){
                returnData=[NSMutableData data];
            }

            NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];


   dispatch_async(dispatch_get_main_queue(), ^ {

 id json = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];

        NSArray *returnArray=[json objectForKey:@"notifications"];

                getNotificationsArrayResponseCallback(returnArray,YES);

            });

        }
        @catch (NSException *exception) {


            dispatch_async(dispatch_get_main_queue(), ^ {

                UIAlertView *alert=[[UIAlertView alloc]initWithTitle:LANGUAGE(@"Unknown error occurred") message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];


                getNotificationsArrayResponseCallback(nil,NO);

            });
        }        
     });
}
  1. If I remove the code where the images are being loaded with asynchImageview then I call call the web service at any time and the response is fast at any time .

    AsynchImageView *userProfileImageView =[[AsynchImageView alloc] initWithFrameURLStringAndTag:CGRectMake(5, 215, 70, 70) :[NSString stringWithFormat:@"%@%@",SERVER_URL,"some url" ];
    
    [userProfileImageView setBackgroundColor:[UIColor clearColor]];
    
    [userProfileImageView loadImageFromNetwork];
    
    [cell addSubview:userProfileImageView];
    

As you can see if I comment the line

[userProfileImageView loadImageFromNetwork];

then I can call the web service any number of times and the response is quick but when the asynchimage view is loading the images and then i call the service then it will time out for that time only . For further calling service works fine .

I think this is the issue with threading or calling serveral url requests at the same time .

like image 521
sajwan Avatar asked May 15 '26 01:05

sajwan


2 Answers

is this the class you are using? AsynchImageView

If so, it doesn't actually look like his NSURLConnection is being handled in the background. It looks like it's on the main thread.

I have used this other library in the past with success AsyncImageView

If you look in this other library, they are using a proper dispatch queue for running the background. The other class doesn't have that.

dispatch_async(dispatch_get_main_queue(), ^(void) {
like image 61
jacob bullock Avatar answered May 19 '26 02:05

jacob bullock


Make custom cell and inside of that cell, put this method

-(void)setImageWithUrl:(NSString *)imageUrl
{
    NSURL *urlImage = [NSURL URLWithString:imageUrl];
    [self.loadingIndicator startAnimating];

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
    dispatch_async(queue, ^{

        NSError* error = nil;
        NSData *imageData = [NSData dataWithContentsOfURL:urlImage options:nil error:&error];

        if(error){
            dispatch_sync(dispatch_get_main_queue(), ^{

                [self.imgVw setImage:[UIImage imageNamed:@"placeholder.png"]];
                [self.loadingIndicator stopAnimating];
                [[NSURLCache sharedURLCache] removeAllCachedResponses];
            });
        }else{
            UIImage *image = [UIImage imageWithData:imageData];
            dispatch_sync(dispatch_get_main_queue(), ^{

                [self.imgVw setImage:image]; 
                [self.loadingIndicator stopAnimating];
                [[NSURLCache sharedURLCache] removeAllCachedResponses];
            });
        }
    });
}

Now, call this in cellForRowAtIndexPath method. Put it inside cell nil condition, so that it does not called everytime you scroll. Make comment in case of any doubt.

if(custCellObj == nil)
{
      NSString *imgUrl = [yourArray objectAtIndex:indexPath.row];
      [custCellObj setImageWithUrl:imgUrl];
}
like image 21
NSPratik Avatar answered May 19 '26 04:05

NSPratik