0

在这里,我从 url 下载图像并将其保存到缓存目录中,我们从缓存路径中获取图像,但它被击中获取图像。是否有任何替代解决方案可以从本地路径获取图像

在这里,我分享了从本地路径获取图像的代码:

NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [NSString stringWithFormat:@"%@/%@", cachePath,[[imageurl componentsSeparatedByString:@"/"]lastObject]];
UIImage *image = [UIImage imageWithContentsOfFile:path];
4

1 回答 1

0

您应该创建一个 NSObject 类来处理图像的下载和缓存。例子

接口文件

        #import <Foundation/Foundation.h>

            @interface ImageCache : NSObject
            {
             UIImage *background;
            }
   @property (nonatomic,retain) UIImage *background;         
            -(void)getImages;
            -(void) storeImages;
            -(void) clearCache;

    @end

执行

    @implementation ImageCache

        @synthesize background;


            - (void) cacheImage: (NSString *) ImageURLString : (NSString *)imageName
            {
                NSURL *ImageURL = [NSURL URLWithString: ImageURLString];

                // Generate a unique path to a resource representing the image you want

                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *docDir = [paths objectAtIndex: 0];
                NSString *docFile = [docDir stringByAppendingPathComponent: imageName];

                // Check for file existence
                if(![[NSFileManager defaultManager] fileExistsAtPath: docFile])
                {
                    // The file doesn't exist, we should get a copy of it

                    // Fetch image
                    NSData *data = [[NSData alloc] initWithContentsOfURL: ImageURL];

                    UIImage *image = [[UIImage alloc] initWithData: data];

                    // Is it PNG or JPG/JPEG?
                    // Running the image representation function writes the data from the image to a file
                    if([ImageURLString rangeOfString: @".png" options: NSCaseInsensitiveSearch].location != NSNotFound)
                    {

                        [UIImagePNGRepresentation(image) writeToFile: docFile atomically: YES];

                    }
                    else if
                    (
                            [ImageURLString rangeOfString: @".jpg" options: NSCaseInsensitiveSearch].location != NSNotFound || 
                            [ImageURLString rangeOfString: @".jpeg" options: NSCaseInsensitiveSearch].location != NSNotFound
                    )
                    {
                        [UIImageJPEGRepresentation(image, 100) writeToFile: docFile atomically: YES];
                    }
                }
            }

            - (UIImage *) getCachedImage : (NSString *)imageName
            {

                NSArray *paths = NSSearchPathForDirectoriesInDomains
                (NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *documentsDirectory = [paths objectAtIndex:0];
                NSString* cachedPath = [documentsDirectory stringByAppendingPathComponent:imageName];

                UIImage *image;

                // Check for a cached version
                if([[NSFileManager defaultManager] fileExistsAtPath: cachedPath])
                {
                    image = [UIImage imageWithContentsOfFile: cachedPath]; // this is the cached image
                }else
                {
                    NSLog(@"Error");
                }

                return image;
            }

        -(void)getImages
        {    
//I just googled background image and took first image I found for this example
         NSString *backgroundURL = @"http://www.dvd-ppt-slideshow.com/images/ppt-background/background-3.jpg";  
        [self cacheImage:backgroundURL: @"Background"];

        }

    -(void) clearCache
    {
    //If you ever need to clear the cache for whatever reason, good to have a method to handle it    
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDir = [paths objectAtIndex: 0];
        NSString *docFile1 = [docDir stringByAppendingPathComponent: @"Background"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:docFile1 error:NULL];

    }

    -(void) storeImages
    {
        background = [self getCachedImage:@"Background"];
    }

@end

在我给出的示例中,我只使用了一张图片。但你明白我敢肯定。现在,如果您想下载并存储该图像。只需在 ViewController 中导入 ImageCache 类,然后调用

ImageCache *cacheMe = [[ImageCache alloc] init];
   [cache getImages];
    [cacheMe storeImages];
    UIImageView *image = [[UIImageView alloc] initWithImage:[cacheMe background]];

这就是您需要做的所有事情。如果你有一个专门用于缓存的类,那就容易多了。希望有帮助!!

编辑:更新忘记了两行代码。我自己测试过,现在应该可以正常工作了

于 2012-08-13T10:11:59.950 回答