Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with two different baseUrl - AFHTTPSessionManager

I am using AFHTTPSessionManager to make api calls on the web. I have signleton object of session manager and it initiates the base url once. Occasionally, I am in a need of making api call with different baseurl. And its readonly in AFNetworking.h file.

What is the proper way of handing different baseurl here? Plese help.

+ (ApiClient *)sharedClient {

    static ApiClient *_sharedClient = nil;

    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{
        _sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:kTraktBaseURLString]];
    });
    return _sharedClient;
}
like image 327
Bharathi Jayakumar Avatar asked Feb 12 '23 12:02

Bharathi Jayakumar


1 Answers

You can use the behaviour of +URLWithString:relativeToURL: method to override baseURL.

Matt mentioned it in Docs

For HTTP convenience methods, the request serializer constructs URLs from the path relative to the baseURL, using NSURL +URLWithString:relativeToURL:, when provided. If baseURL is nil, path needs to resolve to a valid NSURL object using NSURL +URLWithString:.

Below are a few examples of how baseURL and relative paths interact:

NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
[NSURL URLWithString:@"foo" relativeToURL:baseURL];                  //  http://example.com/v1/foo
[NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL];          // http://example.com/v1/foo?bar=baz
[NSURL URLWithString:@"/foo" relativeToURL:baseURL];                 // http://example.com/foo
[NSURL URLWithString:@"foo/" relativeToURL:baseURL];                 // http://example.com/v1/foo
[NSURL URLWithString:@"/foo/" relativeToURL:baseURL];                // http://example.com/foo/
[NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/

So if you want to alter baseURL for single request, you can pass Absolute URL as a URLString argument to GET:parameters:success:failure: instead of URL path.

[manager GET:@"http://otherBaseURL.com/url/path" parameters:nil success:... failure:...]
like image 71
DanSkeel Avatar answered Feb 16 '23 03:02

DanSkeel