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

标签 ios objective-c afnetworking afnetworking-2

我正在按照给定的示例代码

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);
}];

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

- (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;
}

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

最佳答案

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

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

关于ios - 如何在 AFNetworking 2.0 中设置请求超时和缓存策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19953964/

相关文章:

android - React Native MapView 使用相机标题旋转 map

ios - 在 Swift 4 中获取远程通知设备 token ?

objective-c - 在 Cocoa 中生成一个随机的字母数字字符串

ios - 将动态内容写入 xCode 项目 .plist

ios - 使用 AFXAuthClient 时,如何保留 token 并发出进一步的请求?

ios - 如何使用 AFNetworking 2 批量请求?

iOS : Core Data: How to retain an ordered set of objects in a managed object

ios - 在 Xcode "Provisioning Profile"build设置中配置 "Code Signing"选项

ios - 如何将委托(delegate)更改为 NSURLSession

ios - 如何处理 AFHTTPRequestOperation 中的空 responseObject