設置AFNetworking網絡請求的超時時間

也許大家使用的時候已經察覺到,設置AFNetworking的超時時間並不管用,但可以用特殊的方式來處理。
以下是筆者基於AFNetworking2.5.0封裝的GET,POST請求用方法。
POST請求
+ (AFHTTPRequestOperation *)GETMethod:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; // 設置超時時間 [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"]; manager.requestSerializer.timeoutInterval = 10.f; [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"]; AFHTTPRequestOperation *httpOperation = [manager GET:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { if (success) { success(operation, responseObject); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { if (failure) { failure(operation, error); } }]; return httpOperation; }
GET請求
+ (AFHTTPRequestOperation *)POSTMethod:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"]; // 設置超時時間 [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"]; manager.requestSerializer.timeoutInterval = 10.f; [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"]; AFHTTPRequestOperation *httpOperation = [manager POST:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { if (success) { success(operation, responseObject); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { if (failure) { failure(operation, error); } }]; return httpOperation; }
其中,設置這么一句話即可:

