Tuesday, 10 September 2013

How to send request and receive response using ASIHTTPRequest with GCD blocks

Generally requesting for any kind of information we will use traditional programming structure like NSURLConnection(NSURL -> NSURLRequest -> NSURLConnection). Or we can use a latest powerful library ASIHTTP library.

We also use GCD(Grand Central Dispatch) instead of call backing methods for faster and easier purpose. But writing the blocks are bit of difficulty.

Here we are going to use both combination(ASIHTTP+GCD) to get faster results and to avoid anther over headache. Have a look on following code to understand above concept.

Ex:

       [indicatorView startAnimating]; /////////////////// start animating Indicatorviwe to show processing if need.
           
     ////////////////////////// retrieving images from server //////////////////////////////////////
    NSString *strBannerImageURL = [NSString stringWithFormat:@"http://images.dailytech.com/nimage/iPhone_5_AngledSharp_Front_Back_White_PRINT.jpg"]; ////////////////// some image URL string

    NSURL *bannerImageURL = [NSURL URLWithString:strBannerImageURL];
    //NSURL *imageURL = [NSURL URLWithString:objProduct.imageUrls];
    
    dispatch_queue_t downloadQueueBanner = dispatch_queue_create("Image Downloader", NULL);
    dispatch_async(downloadQueueBanner, ^{
        NSData *imageData = [NSData dataWithContentsOfURL:bannerImageURL];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            UIImage *image = [UIImage imageWithData:imageData];
            
            //NSLog(@"imageData: %@", imageData);
            //NSLog(@"IMAGE: %@", image);
            
            if (!image) {
                image = [UIImage imageNamed:@"Apple.png"];
            }
            
            [custImageView setImage:image];  /////// setting image to our own controllers 
            
            //appDelegate.objUser.image = image;
            
            [indicatorView stopAnimating];
            
        });
    });
    dispatch_release(downloadQueueBanner); //won’t actually go away until queueis empty

Thank you for spending your valuable time for this post. Kindly leave comments on it. 


No comments:

Post a Comment