Working with two different baseUrl - AFHTTPSessionManager - objective-c

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;
}

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:...]

Related

Objective-C - Formatting GET request

What are the rules for passing the string parameter such as %JOHN% in a GET request url
my request url is supposed to look like: https://somesite.com/search/name?name=%SEARCH_KEYWORD%
Try#1: I did this
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:#"https://somesite.com/search/name?name=%%%#%%",SEARCH_KEYWORD]];
O/P: nil
Try#2:
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:#"https://somesite.com/search/name?name=%JOE%"]];
**O/P:
https://somesite.com/search/name?name=JOE
Any suggestions?
You can use NSURLComponents to build URLs:
Objective-C:
NSURLComponents *components = [NSURLComponents componentsWithString:#"https://google.com"];
components.query = #"s=%search keywords%"
NSURL *url = components.URL;
Swift (careful with ! in production, I used to test in Playgrounds):
let components = NSURLComponents(string: "https://google.com")!
components = "s=%search keywords%"
let url = components!
print(url) // "https://google.com?s=%25search%20keywords%25"
Also if you need more complex queries NSURLComponent have a queryItems property.
You are making a mistake, just use a single %#.
Example:
NSString *string = #"JOE";
NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:#"https://somesite.com/search/name?name=%#",string]];

Objective-C UIDocumentInteractionController Couldn't issue file extension for path

I am having an issue with UIDocumentInteractionController, here is my code:
NSURL *URL = [NSURL fileURLWithPath:#"http://www.domain.com/pdf/35.pdf"];
//NSURL *URL = [[NSBundle mainBundle] URLForResource:#"35" withExtension:#"pdf"];
if (URL) {
// Initialize Document Interaction Controller
self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:URL];
// Configure Document Interaction Controller
[self.documentInteractionController setDelegate:self];
// Preview PDF
[self.documentInteractionController presentPreviewAnimated:YES];
}
my console log says this:
Couldn't issue file extension for path: /http:/www.domain.com/pdf/35.pdf
and in my app it displays a gray background and says 35.pdf Portable Document Format (PDF)
what am i doing wrong?
An http URL is not a file URL.
This:
NSURL *URL = [NSURL fileURLWithPath:#"http://www.domain.com/pdf/35.pdf"];
needs to be:
NSURL *URL = [NSURL URLWithString:#"http://www.domain.com/pdf/35.pdf"];
But note that UIDocumentInteractionController expects a URL to a local resource, not an Internet URL. So you can't use the above URL at all.
You would need to download and save the PDF file locally first and then create a proper file URL to the local file.

i want to take only simple url without http://

i want to add "http://" inside code so that user find it easy to browse by only typing a simple url
i have tried
- (IBAction)uurl:(id)sender {
NSURL *myurl = [NSURL URLWithString : #"http://"];
}
but its not working
//This is what the user types, depending on the type of input you use
NSString *urlString = #"www.bla.com";
NSString *httpString = #"http://";
urlString = [httpString stringByAppendingString:urlString];
//OR urlString = [NSString stringWithFormat:#"http://%#",urlString];
NSURL *url = [NSURL URLWithString:urlString];
Right this is simple enough to do but we need to check as well if the user inputs the http:// or https:// themselves. So see below with explanation in comments
- (IBAction)uurl:(id)sender
{
// Our to NSStrings that we want to be checking for.
static NSString *httpsStr = #"https://";
static NSString *httpStr = #"http://";
NSString *urlStr = #"www.google.com"; // User input however you take this
// Our check to make sure that the urlStr passed in does already have http or https
if(![urlStr hasPrefix:httpsStr] && ![urlStr hasPrefix:httpStr]) {
// If it doesn't have anything our default HTTP Protocol will be http
urlStr = [NSString stringWithFormat:#"http://%#", urlStr];
}
// If the user has entered the http or https themselves ignore reseting to http
// Set our urlStr as the URL we want to use.
NSURL *url = [NSURL URLWithString:urlStr];
// At this point you would do whatever it is you want to do with the url
}
Use -initWithScheme:host:path:
// your user input string
NSString *userString = #"www.apple.com";
NSURL *yourURL;
if (![userString hasPrefix:#"http://"])
yourURL = [[NSURL alloc] initWithScheme:#"http" host:userString path:#"/"];
else
yourURL = [[NSURL alloc] initWithString:userString];

Objective-C/CocoaHttpServer - Trying to do a simple GET request with one parameter

I'm trying to use the "CocoaHTTPServer" found at https://github.com/robbiehanson/CocoaHTTPServer. I have added it to my project, and now, if i type on my browser something like this: 192.168.3.114:45000 i receive an html page called index with a simple welcome message (this page is stored inside the default project). This is ok. It works correctly. What i need to understand now, is how can i for example do a simple GET request typing on the browser something like "192.168.3.114:52000/getElement" and receive on the browser a simple String. Can you please give me help? I don't know where i can configure or check this because there are some classes. I'm trying to study the HTTPConnection class but i'm going in confusion because i'm new on the objective-c programming.
Thanks
You have to use a custom HTTPConnection subclass
#interface MyHTTPConnection : HTTPConnection
...
#end
then you could do custom URL handling
#implementation MyHTTPConnection
- (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
{
HTTPLogTrace();
if ([path isEqualToString:#"/getElement"])
{
NSData *data = ...
HTTPDataResponse *response = [[HTTPDataResponse alloc] initWithData:data];
return response;
}
// default behavior for all other paths
return [super httpResponseForMethod:method URI:path];
}
#end
and the set HTTPServer connectionClass so that your server knows you want to handle the connections yourself
[httpServer setConnectionClass:[MyHTTPConnection class]];
You can do an NSURL request and then get the server response as an NSString:
NSString *URL = #"http://yoururlhere.com?var1=";
URL = [URL stringByAppendingString: yourvarstring];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: URL]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
//Check if the server has any output
if([serverOutput length] == 0)
{
//Do something
} else {
//Do Something else
}

Parsing NSURL in Objective-C

I have an NSTextView control that could potentially have links in it. How do I get the full url of the link?
Here is what I have so far
-(BOOL)textView:(NSTextView *)aTextView clickedOnLink:(id)aLink atIndex:(NSUInteger)charIndex
{
NSURL *htmlURL = [NSURL fileURLWithPathComponents:[aLink pathComponents]];
}
This gives me a URL that begins with file://localhost ... How do I get rid of that portion of the URL?
NSURL* url = [NSURL URLWithString:#"http://localhost/myweb/index.html"];
NSString* reducedUrl = [NSString stringWithFormat:
#"%#://%#",
url.scheme,
[url.pathComponents objectAtIndex:1]];