AFNetworking 配合NSURLCache 本地缓存

AFNetworking, NSURLCache & iOS 6

NSURLCache can be used to define memory and disk caching for URL requests. If you make a connection while you are not connected to the internet with the cache policy set to NSURLRequestReturnCacheDataElseLoad, data should be returned from the cache if it exists. This works as expected on iOS 5 and cached data is always returned. On iOS 6.x, however, this doesn’t happen and the connection will fail returning an error code -1009 which indicates that you are offline. I ran into this recently while using AFNetworking and apparently this is a bug in iOS 6.x and has already been reported to Apple by multiple people.

To workaround this, I wrote a simple class that subclasses AFNetworking‘s AFHTTPClient (thanks tothis GitHub issue) and ensures that you always get cached data when it’s available regardless of whether you are connected to the internet or not.

What it does is that it gets the NSCachedURLResponse in the failure block of the request you are making and deserializes it using NSJSONSerialization, then calls the success block with the responseObject as if the connection didn’t fail.

I’ve added the code to a GitHub gist. Please fork it if you think there’s something that could be improved.

123456789101112
          
          
//
// HMHTTPClient.h
//
// Created by Hesham Abd-Elmegid on 4/10/13.
// Copyright (c) 2013 Startappz. All rights reserved.
//
 
#import "AFHTTPClient.h"
 
@interface HMHTTPClient : AFHTTPClient
 
@end
view raw HMHTTPClient.h hosted with ❤ by  GitHub
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
          
          
//
// HMHTTPClient.m
//
// Created by Hesham Abd-Elmegid on 4/10/13.
// Copyright (c) 2013 Startappz. All rights reserved.
//
 
#import "HMHTTPClient.h"
 
@implementation HMHTTPClient
 
- ( void ) getPath: ( NSString * ) path
parameters: ( NSDictionary * ) parameters
success: ( void ( ^ )( AFHTTPRequestOperation * operation , id responseObject )) success
failure: ( void ( ^ )( AFHTTPRequestOperation * operation , NSError * error )) failure
{
NSMutableURLRequest * request = [ self requestWithMethod : @"GET" path : path parameters : parameters ];
[ request setCachePolicy : NSURLRequestReturnCacheDataElseLoad ];
AFHTTPRequestOperation * operation = [ self HTTPRequestOperationWithRequest : request success : success failure : failure ];
[ self enqueueHTTPRequestOperation : operation ];
}
 
- ( void ) postPath: ( NSString * ) path
parameters: ( NSDictionary * ) parameters
success: ( void ( ^ )( AFHTTPRequestOperation * operation , id responseObject )) success
failure: ( void ( ^ )( AFHTTPRequestOperation * operation , NSError * error )) failure
{
NSMutableURLRequest * request = [ self requestWithMethod : @"POST" path : path parameters : parameters ];
[ request setCachePolicy : NSURLRequestReturnCacheDataElseLoad ];
AFHTTPRequestOperation * operation = [ self HTTPRequestOperationWithRequest : request success : success failure : failure ];
[ self enqueueHTTPRequestOperation : operation ];
}
 
- ( void ) putPath: ( NSString * ) path
parameters: ( NSDictionary * ) parameters
success: ( void ( ^ )( AFHTTPRequestOperation * operation , id responseObject )) success
failure: ( void ( ^ )( AFHTTPRequestOperation * operation , NSError * error )) failure
{
NSMutableURLRequest * request = [ self requestWithMethod : @"PUT" path : path parameters : parameters ];
[ request setCachePolicy : NSURLRequestReturnCacheDataElseLoad ];
AFHTTPRequestOperation * operation = [ self HTTPRequestOperationWithRequest : request success : success failure : failure ];
[ self enqueueHTTPRequestOperation : operation ];
}
 
- ( void ) deletePath: ( NSString * ) path
parameters: ( NSDictionary * ) parameters
success: ( void ( ^ )( AFHTTPRequestOperation * operation , id responseObject )) success
failure: ( void ( ^ )( AFHTTPRequestOperation * operation , NSError * error )) failure
{
NSMutableURLRequest * request = [ self requestWithMethod : @"DELETE" path : path parameters : parameters ];
[ request setCachePolicy : NSURLRequestReturnCacheDataElseLoad ];
AFHTTPRequestOperation * operation = [ self HTTPRequestOperationWithRequest : request success : success failure : failure ];
[ self enqueueHTTPRequestOperation : operation ];
}
 
- ( AFHTTPRequestOperation * ) HTTPRequestOperationWithRequest: ( NSURLRequest * ) urlRequest
success: ( void ( ^ )( AFHTTPRequestOperation * operation , id responseObject )) success
failure: ( void ( ^ )( AFHTTPRequestOperation * operation , NSError * error )) failure
{
AFHTTPRequestOperation * operation = [ super HTTPRequestOperationWithRequest : urlRequest success : success failure :^ ( AFHTTPRequestOperation * operation , NSError * error ) {
if ( error . code == kCFURLErrorNotConnectedToInternet ) {
NSCachedURLResponse * cachedResponse = [[ NSURLCache sharedURLCache ] cachedResponseForRequest : urlRequest ];
if ( cachedResponse != nil && [[ cachedResponse data ] length ] > 0 ) {
id JSON = [ NSJSONSerialization JSONObjectWithData : cachedResponse . data options : 0 error :& error ];
success ( operation , JSON );
} else {
failure ( operation , error );
}
} else {
failure ( operation , error );
}
}];
return operation ;
}
 
@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值