AFNetworking – a delightful networking library for iOS and Mac OS X

afnetworking

In this post, I will introduce you with AFNetworking, a networking library built for iOS and Mac OS X. As networking became the most common part in every app and the most important feature of all, we have to make sure that we are doing it right and using the best library that exists.

I will show you how to use this library to make network calls by posting the code I am using in every app for a very long period.

 

-(void)requestWithEnd:(NSString *)endUrl method:(NSString *)method params:(NSDictionary *)params callWithSuccess:(void (^)(NSDictionary*response))completionBlock errorCallback:(void(^)(NSError*))errorBlock {
    

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    NSString *url = [self getUrl:endUrl];

    if ([method isEqualToString:@"GET"]){
        [manager GET:url parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
            NSLog(@"JSON: %@", responseObject);
            if (completionBlock) completionBlock(responseObject);
        } failure:^(NSURLSessionTask *operation, NSError *error) {
            NSLog(@"Error: %@", error);
            if (errorBlock) errorBlock(error);
        }];
    }
    else if ([method isEqualToString:@"POST"]){
        [manager POST:url parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
            NSLog(@"JSON: %@", responseObject);
            if (completionBlock) completionBlock(responseObject);
        } failure:^(NSURLSessionTask *operation, NSError *error) {
            NSLog(@"Error: %@", error);
            if (errorBlock) errorBlock(error);
        }];
    }
    else if ([method isEqualToString:@"DELETE"]){
        [manager DELETE:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"JSON: %@", responseObject);
            if (completionBlock) completionBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"Error: %@", error);
            if (errorBlock) errorBlock(error);
        }];
    }
    else if ([method isEqualToString:@"PUT"]){
        [manager PUT:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"JSON: %@", responseObject);
            if (completionBlock) completionBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"Error: %@", error);
            if (errorBlock) errorBlock(error);
        }];
    }

}

 

If you have any questions please comment and I would be really happy to assist you.

 

Leave a Reply

Your email address will not be published. Required fields are marked *