WebService Handler on AFNetworking

Step1

pod 'AFNetworking','~> 2.5'

Step 2

#import "AFNetworking.h"

@interface WebServiceHandler : NSObject

@property(nonatomic,strong)AFHTTPRequestOperationManager *reqOperationManager;


-(void)call:(eMethodType)methodType withUrl:(NSString *)serviceUrl withParameter:(NSDictionary *)parameters onCompletion:(void(^)(eResponseType responseType, id response))completionBlock;


Step 3

#import "WebServiceHandler.h"
#import "Reachability.h"

#define TIME_OUT 60.0f

@implementation WebServiceHandler

-(instancetype)init
{
    self = [super init];
    if (self) {
        
        _reqOperationManager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:kBASE_URL]];
        
    }
    return self;
}

/**
 *  This method creates NSMutableURLRequest and AFHTTPRequestOperation object, start operation. When server response for the same, this identify errorCode, according to this we Display the message for different errorCode. If there is no errorCode, it means it is Succes response, we can perform operatios over that response.    Also we are identifying the responseType here in this method which is being forwarded to subsequest calling methods.
 *
 *
 *  @param serviceUrl      It takes an URL to be hit
 *  @param parameters      and an Parameter as Credential and Data to be append in Body of request
 *  @param completionBlock - When there is respose from the server We call completionBlock.
 *  And pass the Response type and response in case of json response. Otherwise we pass the We Pass the Error Object.
 */


-(void)call:(eMethodType)methodType withUrl:(NSString *)serviceUrl withParameter:(NSDictionary *)parameters onCompletion:(void(^)(eResponseType responseType, id response))completionBlock {
    
    @try {
        
        Reachability *reachability = [Reachability reachabilityWithHostName:@"www.google.com"]; // To test the reachability.
        
        if (reachability.currentReachabilityStatus != NotReachable)
        {
            switch (methodType) {
                case eMethodTypeGET:
                {
                    [self getService:serviceUrl withParam:parameters withSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                        
                        NSLog(@"URL = %@",[operation.request.URL absoluteString]);
                        
                        if ([responseObject objectForKey:errorCode]) {
                            // server response. "status = ERROR"
                            // server sending some errorCode
                            completionBlock(eResponseTypeErrorCodeJSON,responseObject);
                        }else{
                            // Server response in negative :-
                            completionBlock(eResponseTypeSuccessJSON ,responseObject);
                        }
                    } withFailure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        
                        NSLog(@"Fail URL Error = %@, %@",[operation.request.URL absoluteString], error);
                        switch (error.code) {
                            case 404:
                                // Display some messages
                                break;
                            default:
                                // display message based on parameters, error.description
                                break;
                        }
                        completionBlock(eResponseTypeRequestFailure,error);
                    }
                     ];
                }
                    break;
                case eMethodTypePOST:
                {
                    [self postServiceWithJSON:serviceUrl withParam:parameters withSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                        
                        if ([responseObject objectForKey:errorCode]) {
                            // server response. "status = ERROR"
                            // server sending some errorCode
                            completionBlock(eResponseTypeErrorCodeJSON,responseObject);
                        }else{
                            // Server response in negative :-
                            completionBlock(eResponseTypeSuccessJSON ,responseObject);
                        }
                        
                    } withFailure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        
                        NSLog(@"OP = %@, ERROR - %@",operation,error);
                        
                        switch (error.code) {
                            case 404:
                                // Display some messages 
                                break;
                            default:
                                // display message based on parameters, error.description
                                break;
                        }
                        completionBlock(eResponseTypeRequestFailure,error);
                    }];
                }
                    break;
                    
                case eMethodTypeUnknown:
                default:
                    break;
            }
            
        }else{
            // network not reachable
            // No internet connection.
            [self showAlertWithTitle:@"Network Error !" message:@"Please check your Internet Connection !"];
        }
        
    }@catch (NSException *exception) {
        
    }
    @finally {
        
    }
}


-(void) getService:(NSString *)service withParam:(NSDictionary *)param
       withSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))sucess
       withFailure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    
    
    [_reqOperationManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"content-type"];
    [_reqOperationManager.requestSerializer setTimeoutInterval:TIME_OUT];
    _reqOperationManager.responseSerializer.acceptableContentTypes = [_reqOperationManager.responseSerializer.acceptableContentTypes setByAddingObject:@"application/json"];
    [_reqOperationManager GET:service
                   parameters:param
                      success:^(AFHTTPRequestOperation *operation, id responseObject){
                          sucess(operation,responseObject);
                      }
                      failure:^(AFHTTPRequestOperation *operation, NSError *error){
                          failure(operation, error);
                      }];
}

-(void) postServiceWithJSON:(NSString *)service withParam:(NSDictionary *)param
                withSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))sucess
                withFailure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    
    _reqOperationManager.requestSerializer=[AFJSONRequestSerializer serializer];
    [_reqOperationManager.requestSerializer setTimeoutInterval:TIME_OUT];
    [_reqOperationManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"content-type"];
    _reqOperationManager.responseSerializer.acceptableContentTypes = [_reqOperationManager.responseSerializer.acceptableContentTypes setByAddingObject:@"application/json"];
    
    [_reqOperationManager POST:service
                    parameters:param
                       success:^(AFHTTPRequestOperation *operation, id responseObject){
                           
                           sucess(operation,responseObject);
                           
                           
                       }
                       failure:^(AFHTTPRequestOperation *operation, NSError *error){
                           failure(operation, error);
                       }];
}

Comments