AFNetworking AFHTTPClient Class

Bruno Tereso picture Bruno Tereso · Oct 21, 2013 · Viewed 10.1k times · Source

I’m fairly new to iOS programming, especially when it comes to webservices. I’m developing a App for academic purposes, and I need to communicate with my server, currently using AFNetworking2 and Restler/php, everything work when it comes to GET methods. But I can’t upload anything.

Been reading for hours, in github support site, stackoverflow, pretty much all examples/questions to upload images (and there are a LOT) use this line:

AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://server"]]; 

I do have a Client class, subclass of AFHTTPSessionManager, with my sharedClient. But all examples use this AFHTTPClient with initWithURL and other classes like AFJSONRequestOperation that I can’t no longer find.

Mostly it says I should create a singleton, subclass of AFHTTPClient, but I can´t find it anywhere. Some links even send me to official github repository but it’s not available anymore. So my question is, where can I get more info about AFHTTPClient, should I use it, can anyone point me a tutorial on how to create one or at least understand its functionality.

Cheers

Answer

Pradeep Mahdevu picture Pradeep Mahdevu · Oct 21, 2013

In AFNetworking 2.0 the AFHTTPClient has been replaced by AFHTTPRequestOperationManager / AFHTTPSessionManager. I would suggest you to refer to the example in git by them. Git clone and open in XCode. It should help you. That has the most updated example.

If you want to use AFHTTPClient i.e 1.x code. Here is the git link to the branch. The pod spec to that would be

pod 'AFNetworking', '~> 1.3.3'

In 2.0 AFNetworking, you can create a singleton client like this.

interface

@interface AFAppDotNetAPIClient : AFHTTPSessionManager

+ (instancetype)sharedClient;

@end

Implementation

#import "AFAppDotNetAPIClient.h"

static NSString * const AFAppDotNetAPIBaseURLString = @"https://alpha-api.app.net/";

@implementation AFAppDotNetAPIClient

+ (instancetype)sharedClient {
    static AFAppDotNetAPIClient *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[AFAppDotNetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:AFAppDotNetAPIBaseURLString]];
        [_sharedClient setSecurityPolicy:[AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]];
    });

    return _sharedClient;
}

@end