iOS - Increase timeout for AFHTTPRequestOperationManager

后端 未结 5 934
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 09:11

I\'m downloading JSON data from a very slow server. It takes about a minute to get a resoonse from the server. I use AFNetworking library and my code throws \"The request timed

5条回答
  •  误落风尘
    2021-02-04 10:10

    Create a subclass

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

    TimeoutAFHTTPRequestSerializer.h

    #import "AFURLRequestSerialization.h"
    
    @interface TimeoutAFHTTPRequestSerializer : AFHTTPRequestSerializer
    
    @property (nonatomic, assign) NSTimeInterval timeout;
    
    - (id)initWithTimeout:(NSTimeInterval)timeout;
    
    @end
    

    TimeoutAFHTTPRequestSerializer.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
    

提交回复
热议问题