Ankur Kumawat Ankur Kumawat - 4 months ago 33
iOS Question

How to Image array load in UIImageView

I want to image array load in single image view (Images load one by one sam as image slider). I get image array by web server(JSON). I trying to many times but my application is crashed and many time error show. Please help me how to create image slider. Thank You

MY Code



-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;

NSLog(@"Error in receiving data %@",error);
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSLog(@"response data %@",json);

NSArray* results = [json objectForKey:@"status"];
NSArray *imagearray = [results valueForKey:@"slider_image_path"];
NSLog(@"images %@",imagearray);

self.imageview.animationImages = imagearray;
_imageview.animationDuration = 10;
_imageview.animationRepeatCount = 0;
[_imageview startAnimating];
}

Answer

You are getting the image urls from the server and not the images itself, so the imagearray is a collection of urls right now, and you can not directly set the url itself to the animationImages. So what you need to do next is you would need to download the images from the image urls and then set the array (that would contain the instances of UIImage) to the image views animationImages property.

Update

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSError *error;

    NSLog(@"Error in receiving data %@",error);
    NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves  error:&error];
    NSLog(@"response data %@",json);

    NSArray* results = [json objectForKey:@"status"];
    NSArray *imageUrlArray = [results valueForKey:@"slider_image_path"];
    NSLog(@"images %@",imagearray);

    NSMutableArray *arrayImages = [[NSMutableArray alloc] init];

    //Updated for loop, previously in hurry i was setting url string as a url to the URLWithString method, now its working fine.
    for (NSString *strImageUrl in imageUrlArray) {
        [arrayImages addObject:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:strImageUrl]]]];
    }

    self.imageview.animationImages = arrayImages;
    _imageview.animationDuration = 10;
    _imageview.animationRepeatCount = 0;
    [_imageview startAnimating];
}