AFNetworking 2.0:在缓存之前处理数据

时间:2014-02-26 14:31:19

标签: ios objective-c cocoa-touch caching afnetworking

是否有办法更改某些数据 - 更具体地说:图像 - 在缓存之前?

我从一个非常大的api下载图像。我想在它们到达时将它们缩小,以便它们需要更少的空间,并且每次从缓存加载时我都不必缩放它们。

我可以在AFImageResponseSerializer的子类或STAHTTPRequestOperation的子类中进行缩放。但在任何一种情况下,图像都已经以原始大小缓存。

如何在将数据写入缓存之前访问和更改数据?

1 个答案:

答案 0 :(得分:0)

回答我自己的问题:我通过在操作类中覆盖connection:willCacheResponse:来实现它。

@implementation MYImageRequestOperation

-(CGSize)size
{
    return CGSizeZero; // overwritten in subclasses
}



-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{

    UIImage *image = [UIImage imageWithData:cachedResponse.data];
    GPUImageLanczosResamplingFilter *resizingFilter = [[GPUImageLanczosResamplingFilter alloc] init];

    CGFloat scale = [UIScreen mainScreen].scale;
    CGSize size = [self size];
    [resizingFilter forceProcessingAtSizeRespectingAspectRatio: CGSizeMake(size.width * scale, size.height * scale)];
    GPUImagePicture *gpuImage = [[GPUImagePicture alloc] initWithImage:image];
    [gpuImage addTarget:resizingFilter];
    [gpuImage processImage];

    UIImage *smallImage = [resizingFilter imageFromCurrentlyProcessedOutput];

    NSData *data;

    if([[cachedResponse.response.MIMEType lowercaseString] isEqualToString:@"image/png"])
    {
        data = UIImagePNGRepresentation(smallImage);
    } else {
        data = UIImageJPEGRepresentation(smallImage, .9);
    }

    NSCachedURLResponse *response = [[NSCachedURLResponse alloc] initWithResponse:cachedResponse.response data:data];
    return response;
}
@end