How to retrieve images from server asynchronously

后端 未结 5 2063
难免孤独
难免孤独 2021-01-14 06:03

i have one NSMutableArray with some image url\'s. The images have sizes between 12KB to 6MB. I use AsycImageView class and implement but when large

5条回答
  •  情书的邮戳
    2021-01-14 06:08

    you can do this using multiThreading. Here is a code

    - (UIImageView *)getImageFromURL:(NSDictionary *)dict
    {
        #ifdef DEBUG
        NSLog(@"dict:%@", dict);
        #endif
    
        UIImageView *_cellImage = nil;
        _cellImage = ((UIImageView *)[dict objectForKey:@"image"]);
        NSString *strURL = [dict objectForKey:@"imageurl"]);
    
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
    
        #ifdef DEBUG
        NSLog(@"%i", data.length);
        #endif
    
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *dataFilePath = [NSString stringWithFormat:@"%@.png", [documentsDirectory stringByAppendingPathComponent:[dict objectForKey:@"imageid"]]];
    
        if (data) // i.e. file exist on the server
        {
            [data writeToFile:dataFilePath atomically:YES];
            _cellImage.image = [UIImage imageWithContentsOfFile:dataFilePath];
        }
        else // otherwise show a default image.
        {
            _cellImage.image = [UIImage imageNamed:@"nouser.jpg"];
        }
        return _cellImage;
    }
    

    And call this method in cellForRowAtIndexPath like this:

        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:imageURL, @"imageurl", self.imgPhoto, @"image", imageid, @"imageid", nil];
        [NSThread detachNewThreadSelector:@selector(getImageFromURL:) toTarget:self withObject:dict];
    

    The code will start getting images in multiple threads and will save image locally to document folder. Also the image will not download again if already exists with the same name. Hope this helps

提交回复
热议问题