I'm trying to set my base URL for RestKit as http://example.com/api
like so:
// initialize AFNetworking HTTPClient
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/api"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
// initialize RestKit
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];
[RKObjectManager setSharedManager:objectManager];
However for some reason it only saves the domain http://example.com
as the base URL and no following directories after it.
I can simply prepend /api
in front of all my API path calls (e.g. /api/events/active
instead of /events/active
), but it would be a lot easier if I were to eventually work with different versions of the API like (e.g. /v1
). Ideally I would be able to just change the base URL and not so much all the individual paths. Any ideas why I can't set the base URL correctly?
Thanks much! -Ryan
SOLVED:
Base URL was previously stored as "http://example.com/api" and path was "/events".
Thanks to Paul's answer below the correct way is to store base URL as "http://example.com/api/" and path as "events".
Under the hood AFHTTPClient
uses -[NSURL URLWithString:relativeToURL:]
to construct your URLs. If you look at the docs for this method you'll see that it expects a trailing slash. You can get away with this as AFHTTPClient seems to append this for you.
That just leaves us with this potential issue
NSURL *baseURL = [NSURL URLWithString:@"https://example.com/api/"];
NSLog(@"%@", [[NSURL URLWithString:@"/events" relativeToURL:baseURL] absoluteURL]);
//=> https://example.com/events
NSLog(@"%@", [[NSURL URLWithString:@"events" relativeToURL:baseURL] absoluteURL]);
//=> https://example.com/api/events
If you prepend a forward slash it knocks off any path components and just uses the host part of the url. So make sure you don't prepend a slash in your paths