将图像插入设备的缓存 - iOS

时间:2013-06-13 12:07:33

标签: iphone ios objective-c

有没有办法将从网上下载的图像插入设备缓存? 在我的应用程序中,有一些包含图像的视图。在每个桌子上查看有25-30张图片。 问题是图像是在滚动时加载的,结果是滚动图像需要2-3秒才能重新加载...看起来不太好:) 目前,我正在每个小区使用NSURLRequest。

NSURL* url = [NSURL URLWithString:article.articleImage];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) 
{
     if (!error)
     {
         UIImage* image = [[UIImage alloc] initWithData:data];
                                           MainImg.image = image;
                                           article.articleImg=image;
     }

}];

我尝试使用多线程,但启动应用程序需要太长时间。 想法?

4 个答案:

答案 0 :(得分:0)

您好需要UIImageView + AFNetworking.h类别下载和使用AFNetworking你已经排序了

使用其- (void)setImageWithURL:(NSURL *)url方法就像魅力

一样

答案 1 :(得分:0)

您可以将NSURLCache用于此目的。昨天我和我一起工作了,我上课了:

@interface MyURLCache : NSURLCache
@property (nonatomic, assign) NSTimeInterval timeAvaiable;
@end

@implementation MyURLCache

- (id)initWithMemoryCapacity:(NSUInteger)memoryCapacity diskCapacity:(NSUInteger)diskCapacity diskPath:(NSString *)path
{
    self = [super initWithMemoryCapacity:memoryCapacity diskCapacity:diskCapacity diskPath:path];
    if(self){
        _timeAvaiable = 5*60;//5 мин
    }
    return self;
}
- (id)init
{
    self = [super init];
    if(self){
        _timeAvaiable = 5*60;
    }
    return self;
}

+ (NSCachedURLResponse*)addInfoDataToCachedResponce:(NSCachedURLResponse*)cachedResponse
{
    NSMutableDictionary* newUserInfo = [@{@"LastUpdate" : @([[NSDate date] timeIntervalSince1970])} mutableCopy];
    if([cachedResponse userInfo])
        newUserInfo[@"UserInfo"] = [cachedResponse userInfo];

    return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response]
                                                    data:[cachedResponse data]
                                                userInfo:newUserInfo
                                           storagePolicy:[cachedResponse storagePolicy]];
}

+ (NSCachedURLResponse*)removeInfoDataFromCachedResponce:(NSCachedURLResponse*)cachedResponse
{
    return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response]
                                                    data:[cachedResponse data]
                                                userInfo:[cachedResponse userInfo][@"UserInfo"]
                                           storagePolicy:[cachedResponse storagePolicy]];
}

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
    NSCachedURLResponse* result = [super cachedResponseForRequest:request];
    NSDate* lastUpdate = [NSDate dateWithTimeIntervalSince1970:[result.userInfo[@"LastUpdate"] doubleValue]];
    BOOL expired = fabs([lastUpdate timeIntervalSinceNow]) > _timeAvaiable;
    return expired? nil : [[self class] removeInfoDataFromCachedResponce:result];
}

- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request
{
    [super storeCachedResponse:[[self class] addInfoDataToCachedResponce:cachedResponse] forRequest:request];
}

@end

只需在加载应用时启用缓存:

MyURLCache *URLCache = [[MyURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
                                                     diskCapacity:20 * 1024 * 1024
                                                         diskPath:[SDURLCache defaultCachePath]];
[NSURLCache setSharedURLCache:URLCache];

对于每个请求,需要将cachePolicy设置为NSURLRequestReturnCacheDataElseLoad。

或者只使用AFNetworking:)

- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest 
              placeholderImage:(UIImage *)placeholderImage 
                       success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
                       failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;

答案 2 :(得分:0)

在我的所有应用中,我正在使用此框架。使用非常简单

https://github.com/rs/SDWebImage

代码示例

   [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                   placeholderImage:[UIImage imageNamed:@"placeholder.png"]

];

答案 3 :(得分:0)

使用此:

     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
    NSString *savedImagePath = [NSString stringWithFormat:@"%@/%@",[paths objectAtIndex:0],[article.articleImage lastPathComponent]];
    UIImage *image = [UIImage imageNamed:savedImagePath];
    if(!image)
    {
       NSURL* url = [NSURL URLWithString:article.articleImage];
       NSURLRequest* request = [NSURLRequest requestWithURL:url];
       [NSURLConnection sendAsynchronousRequest:request
       queue:[NSOperationQueue mainQueue]
       completionHandler:^(NSURLResponse * response,
       NSData * data,
       NSError * error) 
       {
         if (!error)
         {
            [data writeToFile:savedImagePath atomically:NO]; 
             UIImage* image = [UIImage imageNamed:savedImagePath];
             MainImg.image = image;
             article.articleImg=image;
         }

    }];
  }
else
{
   MainImg.image = image;
   article.articleImg=image;
}
相关问题