Search code examples
iosafnetworking-2

AFNetworking change base url


I am using AFNetworking.

I would like to change baseURL manually.

+ (CustomHTTPClient*)sharedClient{
static dispatch_once_t pred;
static CustomHTTPClient *_sharedClient = nil;



NSLog(@"ShareClient %@",_sharedClient);
if (!_sharedClient)
{
    _sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:@"serverURL"]]];
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
}
else
{

    NSLog(@"Delete ShareClient %@",_sharedClient);
    _sharedClient = nil;

    _sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:@"serverURL"]]];
    NSLog(@"NEW ShareClient %@",_sharedClient);
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

}


return _sharedClient;
}

Option 2:

+ (CustomHTTPClient*)sharedClient{
static dispatch_once_t pred;
static CustomHTTPClient *_sharedClient = nil;


dispatch_once(&pred, ^{
    _sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:@"serverURL"]]];
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
});

return _sharedClient;
}

Option 1: This will create shareclient everytime. So it will use correct (new) BaseURL all time. Option 2: only called onces so BaseURL will be same all time.

Quation:What will be implication of using option 1 instead of Option 2?

I have also check some other answers but would like to understand(in simple terms) why to use Dispatch_once and how to make dispatch_once get called multiple time?

changing AFNetworking baseURL


Solution

  • If you're switching between base URL's it might just be easier to initialise a new manager each time rather than use a shared one. As much of the benefit of using a shared manager is the single static base URL.

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    

    The point of dispatch once is to execute the block only a single time.