如何禁用afnetworking的使用缓存

之前一直在使用ASIRequest作为网络库,但是由于其停止更新,7上可能出现更多的问题,于是决定更换网络库。
目前比较流行的网络库主要有AFNetworking和MKNetworkKit,经过一番google后,得出这三个库之间的比较如下:
AFNetworking
MKNetworkKit
ASIHTTPRequest
维护和使用者相对多
维护和使用者相对少
支持iOS和OSX
否,可通过AFDownloadRequesttion
只支持异步
图片缓存到本地
否,通过SDURLCache或AFCache
图片缓存到
否,可通过AFDownloadRequestOperation
缓存离线请求
否,通过SDURLCache或AFCache
根据以上对比,AFNetworking虽然相比MKNetworkKit功能要弱一些,但是它的更强,而且维护者比较多,从长期来看要优于MKNetworkKit。
以上对比是根据本人测试及查资料所得,如有不正确的地方还希望大家指出,谢谢!如何设置超时与AFNetworking-objective-c_百度知道
如何设置超时与AFNetworking-objective-c
提问者采纳
1. 更改间隔几乎可以肯定不是你所描述的问题的最佳解决方案。相反,它似乎是你真正想要的是HTTP客户端来处理遥不可及,不是吗?AFHTTPClient已经有一个内置的,让你知道什么时候丢失连接,-setReachabilityStatusChangeBlock:。 请求可能需要很长的最好是到iOS知道如何处理连接速度慢,并告诉和无连接的所有的区别。 为了扩大我的推理,为什么其他在这个线程应该避免的,这里有几个想法: 他们甚至开始之前请求可以被取消。入队请求不保证它实际上启动时的担保。 间隔不应该取消长时间运行的请求,尤其是POST。试想一下,如果你试图下载或上传一个100MB的视频。如果请求被沿在最佳状态回事缓慢3,为什么你会不必要地阻止它,如果它采取多一点的时间比预期? 干performSelector:afterDelay:...可以在多线程应用程序。这将打开自己最多晦涩和难以调试的竞争条件。 2. 我强烈看上面mattt的答案-尽管这个答案并不属于一般的问题犯规,原海报的问题,检查可访问性是一个更好的选择 但是,如果你仍然想设置一个(没有所有固有的问题performSelector:afterDelay:等,然后拉入请求描述了一个办法做到这一点作为你只是做之一:NSMutableURLRequest *request = [client requestWithMethod:@&GET& path:@&/& parameters:nil];[request setTimeoutInterval:120];AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:^{...} failure:^{...}];[client enqueueHTTPRequestOperation:operation];但看到警告@,它似乎苹果不容许这种POST请求被改变(这是固定的iOS 6及以上)。 正如@ChrisopherPickslay指出,这不是一个整体它是一个接收(或发送数据)之间。我不知道有什么方法可以理智地做一个全面的苹果说: 该时间间隔,以秒为单位。如果在连接期间尝试 要求保持空闲的时间超过间隔时间越长,要求 被认为具有出去。默认时间间隔为60 秒。 3. 终于找到了如何用POST请求做到这一点:- (void)timeout:(NSDictionary*)dict { NDLog(@&timeout&); AFHTTPRequestOperation *operation = [dict objectForKey:@&operation&]; if (operation) {
[operation cancel]; } [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount]; [self perform:[[dict objectForKey:@&selector&] pointerValue] on:[dict objectForKey:@&object&] with:nil];}- (void)perform:(SEL)selector on:(id)target with:(id)object { if (target && [target respondsToSelector:selector]) {
[target performSelector:selector withObject:object]; }}- (void)doStuffAndNotifyObject:(id)object withSelector:(SEL)selector { // AFHTTPRequestOperation asynchronous with selector
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
@&doStuff&, @&task&,
nil]; AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:baseURL]]; NSMutableURLRequest *request = [httpClient requestWithMethod:@&POST& path:requestURL parameters:params]; [httpClient release]; AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease]; NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
operation, @&operation&,
object, @&object&,
[NSValue valueWithPointer:selector], @&selector&,
nil]; [self performSelector:@selector(timeout:) withObject:dict afterDelay:timeout]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(timeout:) object:dict];
[[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
[self perform:selector on:object with:[operation responseString]]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NDLog(@&fail! \nerror: %@&, [error localizedDescription]);
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(timeout:) object:dict];
[[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
[self perform:selector on:object with:nil]; }]; NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease]; [[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount]; [queue addOperation:operation];}我通过让我的服务器测试此代码sleep(aFewSeconds)。 如果你需要做一个POST请求,不使用[queue waitUntilAllOperationsAreFinished];。该方法作为请求并等待您的选择传递函数被触发 4. 我认为你必须修补的手动在 我继承AFHTTPClient,改变了- (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters方法通过添加[request setTimeoutInterval:10.0];在AFHTTPClient.m线236。 当然,这将是一件好事,如果是可配置的,但据我看到,是不可能的 5. 基于别人的答案,并就相关项目问题@mattt的建议,这里是一个下拉式的匆匆,如果你继承AFHTTPClient:@implementation SomeAPIClient // subclass of AFHTTPClient// ...- (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters { NSMutableURLRequest *request = [super requestWithMethod:method path:path parameters:parameters]; [request setTimeoutInterval:120];}- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters constructingBodyWithBlock:(void (^)(id &AFMultipartFormData& formData))block { NSMutableURLRequest *request = [super requestWithMethod:method path:path parameters:parameters]; [request setTimeoutInterval:120];}@end测试工作在iOS 6。 6. 现在已有上该功能pull请求。请参阅 7. 我们不能这样做有一个是这样的: 在h文件{NSIAFJSONRequestOperation *}在m文件-(void)AFNetworkingmethod{ time = 0; NSTtimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(startTimer:) userInfo:nil repeats:YES]; [timer fire];operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
[self operationDidFinishLoading:JSON]; } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
[self operationDidFailWithError:error]; }]; [operation setJSONReadingOptions:NSJSONReadingMutableContainers]; [operation start];}-(void)startTimer:(NSTimer *)someTimer{ if (time == 15&&![operation isFinished]) {
[operation invalidate];
[operation cancel];
NSLog(@&Timeout&); } ++}转载仅供参考,版权属于原作者。祝你愉快,满意请采纳哦
资深电脑人
其他类似问题
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁AFNetworking&2.0&新特性讲解之AFHTTPSessionManager
AFNetworking 2.0 相比1.0 API
接口改动还是很大的. 其中一个便是&AFURLSessionManager,当然如果你不太熟悉,或者为了兼容低版本,你依然可以选择AFHTTPRequestOperationManager,AFURLSessionManager是基于
NSURLSessionConfiguration(IOS 7.0+, MAC
OX10_9+)的.
下面我们借用TuneStore的API 来完成AFURLSessionManager的讲解.
如果您在看这边文章之前 我建议您首先阅读下AFNetworking2.0的官方新特性介绍.
&- 你如果之前用过AF1.0
这个是很有必要来看的.
另外T*witer 上说NSHipster的AFNetworking现在翻译成中文了,所以我搬过来了有兴趣的朋友也可以去看下,
1:创建 client search
#import "AFHTTPSessionManager.h"
@interface ITunesClient : AFHTTPSessionManager
+ (ITunesClient *)sharedClient;
- (NSURLSessionDataTask *)searchForTerm:(NSString *)term completion:( void (^)(NSArray *results, NSError *error) )completion;
#import "ITunesClient.h"
@implementation ITunesClient
+ (ITunesClient *)sharedClient {
static ITunesClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURL *baseURL = [NSURL URLWithString:@"/"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config setHTTPAdditionalHeaders:@{ @"User-Agent" : @"TuneStore iOS 1.0"}];
& & & &&//设置我们的缓存大小 其中内存缓存大小设置10M& 磁盘缓存5M
NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:10 * 1024 * 1024
diskCapacity:50 * 1024 * 1024
diskPath:nil];
[config setURLCache:cache];
_sharedClient = [[ITunesClient alloc] initWithBaseURL:baseURL
sessionConfiguration:config];
_sharedClient.responseSerializer = [AFJSONResponseSerializer serializer];
return _sharedClient;
- (NSURLSessionDataTask *)searchForTerm:(NSString *)term completion:( void (^)(NSArray *results, NSError *error) )completion {
NSURLSessionDataTask *task = [self GET:@"/search"
& & & & & & & & & & & & & & & & &&//为了速度我们将地区设置为台湾
parameters:@{ @"country" : @"TW",
@"term" : term }
success:^(NSURLSessionDataTask *task, id responseObject) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
if (httpResponse.statusCode == 200) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(responseObject[@"results"], nil);
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, nil);
NSLog(@"Received: %@", responseObject);
NSLog(@"Received HTTP %d", httpResponse.statusCode);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, error);
return task;
Note:为了便于对这个任务进行(取消,监控等)操作
我们将这个任务返回.
controller对client进行回调
NSURLSessionDataTask *task = [[ITunesClient sharedClient] searchForTerm:term
completion:^(NSArray *results, NSError *error) {
if (results) {
self.results = results;
[self.tableView reloadData];
NSLog(@"ERROR: %@", error);
&AFNetworking UIKit 之 加载网络图片
每一个cell
我们可以利用 AFNetworking对UIImageView的&category&.只需要在文件中导入&#import
"UIImageView+AFNetworking.h"&,然后&cellForRowAtIndexPath:方法下直接使用即可
cell.artworkImageView.image = nil;
[cell.artworkImageView cancelImageRequestOperation];
NSURL *imageURL = [NSURL URLWithString:record[@"artworkUrl100"]];
if (imageURL) {
[cell.artworkImageView setImageWithURL:imageURL];
4:当任务运行时显示 activity
indicator&
导入 #import
"UIActivityIndicatorView+AFNetworking.h"&
[self.activityIndicator setAnimatingWithStateOfTask:task];
运行效果如下&
<img src="/blog7style/images/common/sg_trans.gif" real_src ="/mw690/a43af4ffjw1ebkqnxgyf7g208w0dxwiv.gif" ALT="" STYLE="border-style: max-width: 100%;"
TITLE="AFNetworking&2.0&新特性讲解之AFHTTPSessionManager" />
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。AFNetwork缓存 - 互联万物 - ITeye技术网站
博客分类:
AFNetworking uses NSURLConnection which uses NSURLCache shared cache. AFNetworking absolutely transparent in cache regard and doesn't do anything specific. My requests are https and were caching just fine.
Cache-Control response directives allow an origin server to override the default cacheability of a response: private Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache. This allows an origin server to state that the specified parts of the response are intended for only one user and are not a valid response for requests by other users. A private (non-shared) cache MAY cache the response. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.1
If acceptable try to change policy to public . Log headers on response from the app and look at your cache.db and see if in fact something is caching there.
Try to configure shared cache - something along the lines of
int cacheSizeMemory = 1*; // 4MB
int cacheSizeDisk = 100*; // 100MB
[[NSURLCache sharedURLCache] setMemoryCapacity:cacheSizeMemory];
[[NSURLCache sharedURLCache] setDiskCapacity:cacheSizeDisk];
Another good read about this here /blog/2012/nsurlcache-uses-a-disk-cache-as-of-ios5/
浏览: 154132 次
来自: 上海
这个现在已经广泛使用了嘛!
非常之详细
美女求认识
为什么不好使呢?

我要回帖

更多关于 afnetworking教程 的文章

 

随机推荐