Extending NSMutableURLRequest with custom fields - ios

I want to add additional fields to NSMutableURLRequest (for exapmle NSString value requestID) in order to determine correct handler for request when NSURLSession completes it.
Is it legal to create a custom NSMutableURLRequest's subclass to add specific fields? Apple documentation has no additional information about NSMutableURLRequest subclassing.
UPDATE:
I discovered that NSMutableURLRequest subclassing is not the best idea: background NSURLSession can't create download task using my custom subclass object: method downloadTaskWithRequest: always returns nil. I think this problem related with mutableCopyWithZone: that called by NSURLSession when it creates download task with request's copy.
Thanks.

I had no problem creating the task with my subclass, but when I tried to access my custom field from task.originalRequest I discovered it is a NSMutableURLRequest, not my custom subclass.

Instead of extending NSMutableRequest, I would Suggest create basic N/w call handler which would accept your custom parameter.
In this class itself you can use NSMutableRequest to create findal Request with given paramters.
This class can be used application wide to serve you response / data for any request.

I think that if Apple does not provide any warning of subclassing a class, then you can do it.

Related

NSURLSessionResponseCancel produces error?

I used NSURLConnectionobject and called its method cancel sometimes.
Now I should replace NSURLConnection -> NSURLSession. NSURLSession operates with tasks which have cancel method too.
The problem is -[NSURLConnection cancel] just stop the handling of requests but if I use -[NSURLSessionTask cancel] it produces "cancelling error". So how to properly distinguish if cancel is called manually or if a real error is occurred?
I've found 3 solutions:
subclass task/session class
create a custom property via method swizzling in task/session class
the simplest but not very beautiful way - task has string property taskDescription and documentation says that developers are free to use it as they want.
Compare the error code to NSURLErrorCancelled. This error code is generated only when your code cancels the request.

Overriding a NSMutableUrlRequest static initializer?

Heres my scenario. Most of my network calls now need to have an api key inserted into the header field when making a request. So what i was thinking i could do was make a category of NSMutableUrlRequest. Override one of the initalizers. Then in that one initializer i could set the api key as a header field. So everytime i create an object of NSMUTABLEURLREQUEST the header field i need is already set. If you look at the apple doc here NSMutableUrlRequest you can see that the object has 4 initializers 2 class and 2 instance methods. Ill list my questions
What initializer function should i override in order to complete my task? The class or the instance ones?
How can i override it? Either if its an instance or class initializer?
Is this even a good way to go about it? or should i just subclass it and override it like that?
My code has been written for sometime now and well i dont want to go back and insert the api key into each individual request because well theres a lot of them. In a way i think this is a better approach to it because ill just have to set the apiKey in one place and not many place, which lessens the probability of a programming errors.Thank you for your help.
P.S. Even if this isnt a good way to complete this can someone still show me how a class initializer works? Like whats the underlying code so i can generate my own static class initializers also. Each time i try to override the class method i cant figure out what type to return.
Thank you for your help
Categories are not meant to be used to override. You use categories when you want to add additional functionality to existing classes. If you really want to override the initializers then use inheritance.
The static functions are not initializers, they are just helper functions that creates the instance for you, so there's no need to handle them. The simple initWithURL: method is just a simplified version which provide default values for the designated initializer initWithURL:cachePolicy:timeoutInterval:; so in your subclass you actually only need to override this single initializer, looking something like this:
#interface MyNSMutableURLRequest : NSMutableURLRequest
#end
#implementation MyNSMutableURLRequest
- (instancetype)initWithURL:(NSURL *)URL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval {
self = [super initWithURL:URL cachePolicy:cachePolicy timeoutInterval:timeoutInterval];
if (self) {
//do your stuff here
}
return self;
}

iOS: passing custom NSURL to NSURLProtocol

I need to pass some extra informations along with UIWebView loadRequest: so that it reaches my implementation of NSURLProtocol. The information cannot be bound to NSURLRequest because the information must be retained with NSURLRequest mainDocumentURL as well. So i subclassed NSURL and constructed NSURLRequest with it. I already knew that the NSURLRequest which reaches NSURLProtocol startLoading is NOT the instance i have fed to UIWebView loadRequest, so i implemented NSURL copyWithZone too, naively expecting that URL loading system will use it.
Now, NSURLProtocol canInitWithRequest is called not once as one would reasonably expect, but at least 4 times before startLoading. First 2 times of that, the incoming NSURLRequest still contains my custom NSURL implementation. Then an unfortunate internal code called CFURLCopyAbsoluteURL asks for the absoluteURL of my custom NSURL and the next canInitWithRequest (and subsequent startLoading) already gets a completely new NSURLRequest with fresh NSURL in it. copyWithZone is never called and my subclassed NSURL is lost.
Before i give up and implement an inferior and fragile solution with attaching stuff directly to the URL string, i would like to ask the wizards of higher level, whether they see a way how to catch that initial blink on the NSURLProtocol radar or how to trick CFURLCopyAbsoluteURL into carrying my custom instance. I have tried to hack NSURL absoluteURL by returning again a new instance of my custom NSURL class, but it didn't help. I have seen some promise in NSURLProtocol setProperty functionality, but now it appears pretty useless. URL loading system creates new instances of everything happily and NSURLRequest arrived in NSURLProtocol seems to be the same as the one entered into UIWebView only accidentally.
UPDATE: ok i wanted to keep the post as short as possible, but the even the first reply is asking for technical background, so here we go: i've got multiple UIWebViews in app. These views may run requests concurrently and absolutely can run requests for the same URL. It's like tabs in desktop browser. But i need to distinguish which UIWebView was the origin of each particular NSURLRequest arriving to the NSURLProtocol. I need a context being carried with each URL request. I can't simply map the URLs to data, because multiple UIWebViews may be loading the same URL at any moment.
UPDATE 2: Attaching the context information to NSURL is preferred and, as far as my understanding goes, the only usable. The issue is that requests for resources referenced inside page (images etc.) do not go through UIWebViewDelegate at all and end up in NSURLProtocol directly. I don't have a chance to touch, inspect or modify such requests anywhere prior to NSURLProtocol. The only contextual link for such requests is their NSURLRequest mainDocumentURL.
If there's some way to get your original NSURL used as mainDocumentURL that would be ideal. If there's no way to prevent it being copied, I thought of the following hack as an alternative:
Before the creation of each UIWebView, set the user agent string to a unique value. Supposedly this change only affects UIWebView objects that are created subsequently, so each view will end up with its own distinctive user agent string.
In the NSURLProtocol implementation, you can check the user agent string to identify the associated UIWebView and pass it through to the real protocol handler using the actual user agent string (so the server will see nothing different).
All this depends on the views really ending up with different UA strings. Let me know if you manage to get it to work!
You say that you can't put it on the NSURLRequest, but I'm not clear why from your updated discussion. That would be the most natural place to put it.
Implement webView:shouldLoadWithRequest:navigationType:.
Attach an extra property to the provided request using objc_setAssociatedObject. Then return YES. (It would be nice to use setProperty:forKey:inRequest: here, but UIWebView passes us a non-mutable request, so we can only attach associated objects. Yet another way that UIWebView is a pale shadow of OS X's WebView, which can handle this).
In the NSProtocol, read your extra property using objc_getAssociatedObject. The request should be the same one you were presented earlier. You suggest that this isn't the case. Are you saying that the request at webView:shouldLoadWithRequest:navigationType: is different than the request at initWithRequest:cachedResponse:client:?
Am I missing another requirement or quirk?
You can pass options through custom request headers, assuming that the targeted website or service provider don't somehow strip those in transit.
The challenge there would be coming up with an encoding scheme that can be reasonable encoded into an ASCII string for the header field value and then decoded into the actual value you want. For this, a custom NSValueTransformer would seem most appropriate.
I had the same problem. I finally stuck to the solution suggested by Matthew (using the user agent string). However, as the solution is not fleshed out, I add a new answer with more details. Furthermore, I found out that you do not need to send a request to make the user agent "stick". It is sufficient to get via javascript as suggested here.
Following steps worked for me:
(1) Get the current default user agent. You need it later to put it back into the request in NSURLProtocol. You need to use a new webview insatnce, as getting the user agent will make it stick to the webview, so you can not change it later on.
UIWebView* myWebview = [[UIWebView alloc] init];
NSString* defaultUserAgent = [myWebview stringByEvaluatingJavaScriptFromString:#"navigator.userAgent"];
[myWebview release]; // no needed with ARC, but to emphasize, that the webview instance is not needed anymore
(2) Change the value in the standardUserDefaults (taken from here).
NSDictionary* userAgentDict = [NSDictionary dictionaryWithObjectsAndKeys:#"yourUserAgent", #"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:userAgentDict];
(3) Make the new user agent string stick to your webView by getting it via javascript as done in (1), but this time on the webview instance you actually work with.
(4) Revert the default user agent in the standardUserDefaults as done here.

How to create a AFHttpClient with different parameterEncoding for different Request Methods?

I'm new to AFNetworking but so far liking the abstraction.
I'm creating a subclass of AFHttpClient and I'd like to set the parameter encoding to JSON but ONLY for POST requests, is this possible?
You can do this by overriding requestWithMethod:path:parameters:, and setting the parameter encoding according to the specified method. Since all requests created by the client go through this method, it will work as expected.

How to read the response headers every time using AFNetworking?

While using a 3rd party API, I have the requirement to cancel all traffic when a custom response header is set to a certain value. I am trying to find a nice place to do this check only once in my code (and not in every success/failure block, where it works fine). From what I understand, this could be done by overriding -(void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation in my custom AFHTTPClient subclass, but when I implement it like that:
-(void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation
{
NSLog(#"[REQUEST URL]\n%#\n", [operation.request.URL description]);
NSLog(#"[RESPONSE HEADERS]\n%#\n", [[operation.response allHeaderFields] descriptionInStringsFileFormat]);
[super enqueueHTTPRequestOperation:operation];
}
the response headers are nil. Can anybody help me with that?
At the moment when operations are being created and enqueued in AFHTTPClient, they will not have the response from the server--that will be assigned when the request operation is actually executed.
Although the requirement to cancel all traffic seems unorthodox (at least if outside of the conventions of HTTP), this is easy to accomplish:
In your AFHTTPClient subclass, add a BOOL property that stores if requests should be prevented, and then used in enqueueHTTPRequestOperation. Then, override HTTPRequestOperationWithRequest:success:failure: to execute the specified success block along with some logic to set the aforementioned property if the salient response is present.

Resources