如何在不使用SDImageCache的情况下实现延迟加载图像?

时间:2016-10-15 12:49:25

标签: objective-c

如何在不使用以下链接的情况下实现延迟加载图像:

https://packagist.org/packages/tymon/jwt-auth

注意:我不想使用任何第三方工具。我想从我这边做。

2 个答案:

答案 0 :(得分:0)

如果您不想使用任何库(有些是MIT或公共域许可的,那么我认为不使用它们的唯一原因是您想学习如何自己构建它。)

以下是一种简单有效的方法:

1:在imageView中放置一个临时占位符图片。

2:在后台主题中获取您的图片。

2-a :如果您想要缓存功能,请搜索缓存的图像。

2-b:如果没有缓存功能或没有缓存图像,请从其来源获取图像。

2-c:如果缓存功能,请将图像保存到缓存中。

3:在主线程中,在imageView中显示您的图片。

伪代码 :(我在旅途中写了它,它不是为了运行它可能有错误,对不起)。

-(void) lazilyLoadImageFromURL :(NSURL *)url{
    imageView.image = [UIImage imageNamed:@"Placeholder.png];


if([self cachedImageAvailableForURL:url){

imageView.image= [self cachedImageForURL:url];

}
else{

NSOperationQueue *queue = [NSOperationQueue mainQueue];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse * resp, NSData     *data, NSError *error) 
{
    dispatch_async(dispatch_get_main_queue(),^ 
                   {
                        if ( error == nil && data )
                        {
                            UIImage *urlImage = [[UIImage alloc] initWithData:data];
                            imageView.image = urlImage;
                            [self saveImageInCache:image forURL:url];
                            }
                       });
    }];
}

}

-(BOOL) cachedImageAvailableForURL:(NSURL*):url{
        // check if there is a saved cached image for this url
 }
-(UIImage *) cachedImageForURL:(NSURL*):url{
        // returns the cached image for that url
}
-(void) saveImageInCache:(UIImage*) image forURL:(NSURL*)url{
        // saves the image in cache for the url
}

当然,这只是一种可能的方式。我试图让它变得简单,但有更好,更复杂的方法来做到这一点。

答案 1 :(得分:0)

试一试:

       NSURL *imageURL = [NSURL URLWithString:@"www...."];

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

                NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

                dispatch_async(dispatch_get_main_queue(), ^{
                    // Update the UI
                    self.imgVWprofile.image=[UIImage imageWithData:imageData];
                });
            });