ios 如何在 AFNetworking 2.0 中设置请求超时和缓存策略?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19953964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:54:23  来源:igfitidea点击:

How do I set a request timeout and cache policy in AFNetworking 2.0?

iosobjective-cafnetworkingafnetworking-2

提问by joao

I'm following the given example code

我正在遵循给定的示例代码

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

To change the timeout and cache policy I 'hacked' the library and created

为了更改超时和缓存策略,我“入侵”了库并创建了

- (AFHTTPRequestOperation *)GET:(NSString *)URLString
                     parameters:(NSDictionary *)parameters
                          timeoutInterval:(NSTimeInterval)timeoutInterval
                    cachePolicy:(NSURLRequestCachePolicy)cachePolicy
                        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];
    [request setTimeoutInterval:timeoutInterval];
    [request setCachePolicy:cachePolicy];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self.operationQueue addOperation:operation];

    return operation;
}

Is there a clean way of doing this?

有没有干净的方法来做到这一点?

回答by LordParsley

I'm a bit lazy to categorize or subclass. You can access the manager's request serializer directly:

我有点懒于分类或子类化。您可以直接访问管理器的请求序列化程序:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer.timeoutInterval = INTERNET_TIMEOUT;
manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;

回答by Peter Lapisu

The best is to create a subclass

最好是创建一个子类

(you can also the same way add cache policy)

(你也可以用同样的方式添加缓存策略)

TimeoutAFHTTPRequestSerializer.h

超时AFHTTPRequestSerializer.h

#import "AFURLRequestSerialization.h"

@interface TimeoutAFHTTPRequestSerializer : AFHTTPRequestSerializer

@property (nonatomic, assign) NSTimeInterval timeout;

- (id)initWithTimeout:(NSTimeInterval)timeout;

@end

TimeoutAFHTTPRequestSerializer.m

超时AFHTTPRequestSerializer.m

#import "TimeoutAFHTTPRequestSerializer.h"

@implementation TimeoutAFHTTPRequestSerializer

- (id)initWithTimeout:(NSTimeInterval)timeout {

    self = [super init];
    if (self) {
        self.timeout = timeout;
    }
    return self;

}

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
                                 URLString:(NSString *)URLString
                                parameters:(NSDictionary *)parameters
                                     error:(NSError *__autoreleasing *)error
{
    NSMutableURLRequest *request = [super requestWithMethod:method URLString:URLString parameters:parameters error:error];

    if (self.timeout > 0) {
        [request setTimeoutInterval:self.timeout];
    }
    return request;
}

@end

Use

self.requestOperationManager.requestSerializer = [[TimeoutAFHTTPRequestSerializer alloc] initWithTimeout:30];

回答by Pierre Marty

You can also create a category AFHTTPRequestOperationManager+timeout to add this method without having to subclass AFHTTPRequestOperationManager.

您还可以创建一个类别 AFHTTPRequestOperationManager+timeout 来添加此方法,而无需子类化 AFHTTPRequestOperationManager。

回答by arturgrigor

Take a look at Method 1for a cleaner wayto do it: https://stackoverflow.com/a/21238330/435040

看一下方法 1以获得更清晰的方法https: //stackoverflow.com/a/21238330/435040

The difference is that I'm using subclassing and I'm not patching AFNetworking's code.

不同之处在于我使用的是子类化,而不是修补 AFNetworking 的代码。

One thing that I forgot to mention. In that answer I'm only changing the timeout interval, but adding some other caching policy is just 1 more line of code.

一件事我忘了提。在那个答案中,我只是更改了超时间隔,但添加一些其他缓存策略只是多 1 行代码。

回答by user3465357

Try something like :

尝试类似:

NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kRequestTimout];

where kRequestTimoutis the timeout duration you want

kRequestTimout你想要的超时持续时间在哪里

Then build your serialized request :

然后构建您的序列化请求:

NSURLRequest *serializedRequest = [self.requestOperationManager.requestSerializer requestBySerializingRequest:request withParameters:parameters error:&error];

And create & add your request operation :

并创建和添加您的请求操作:

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:serializedRequest];
[operation setCompletionBlockWithSuccess:successBlock failure:failureBlock];
[self.requestOperationManager.operationQueue addOperation:operation];