Search code examples
ios8singletonafnetworkingafnetworking-2

Change Base URL of AFHTTPSessionManager


I have created a subclass of AFHTTPSessionManager with a singleton (code below) but now I need to adjust the Base URL based on the users location (to call a different server in a different part of the world based on the users location). It seems like most examples of this class use a singleton which does not allow you to adjust the base URL (read only property). Is there an easy way for me to adjust the base URL using AFHTTPSessionManager?

 + (RebelBaseManager *)sharedRebelBaseHTTPClient; {

static RebelBaseManager *_sharedRebelBaseHTTPManager = nil;

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{

    _sharedRebelBaseHTTPManager = [[self alloc] initWithBaseURL:[NSURL URLWithString:baseURL];
    _sharedRebelBaseHTTPManager.securityPolicy.allowInvalidCertificates =YES;
});
return _sharedRebelBaseHTTPManager;

}

Solution

  • For those interested here is the method I created that I call whenever I need to adjust the Base URL for a call using AFHTTPSessionManager

    - (AFHTTPSessionManager *) createNewSessionManager {
    
    //Load User Defaults
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    //Create url based on user location
    AFHTTPSessionManager *newDataCall = nil;
    if (![userDefaults valueForKey:@"baseURL"]) {
        [userDefaults setObject:@"https://BASE-URL" forKey:@"baseURL"];
    }
    newDataCall = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:[userDefaults valueForKey:@"baseURL"]]];
    newDataCall.securityPolicy.allowInvalidCertificates =YES;
    newDataCall.responseSerializer = [AFJSONResponseSerializer serializer];
    newDataCall.requestSerializer = [AFJSONRequestSerializer serializer];
    
    return newDataCall;
    }