I need to modify response headers in an NSURLResponse. Is this possible?
A:
You can read them into a NSDictionary using the allHeaderFields
method.
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSDictionary *httpResponseHeaderFields = [httpResponse
allHeaderFields];
To be 100% safe you'd want to wrap it with
if ([response respondsToSelector:@selector(allHeaderFields)]) {... }
sw
2010-01-19 20:12:44
Doesn't that return an NSDictionary instead of an NSMutableDictionary?
Combat
2010-01-19 20:15:20
Yeah, that's what is there in the code sample. Here's the class reference http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSHTTPURLResponse_Class/Reference/Reference.html#//apple_ref/occ/instm/NSHTTPURLResponse/allHeaderFields
sw
2010-01-19 20:30:03
I don't see how an immutable dictionary will help me modify the keys/values
Combat
2010-01-19 20:34:46
Ah... sorry, my mistake - what exactly are you trying to do by modifying the response? You could create a new NSMutableDictionary and use setDictionary to put the values from the original response headers, but I still don't understand the final goal here.
sw
2010-01-19 21:07:11
Use NSMutableDictionary *httpResponseHeaderFields = [[httpResponseallHeaderFields] mutableCopy]; But really we could all help you much more if you would tell us WHY you want to modify fields in a response... are you looking to "fool" some kind of library getting back an NSHTTPURLResponse?
Kendall Helmstetter Gelner
2010-01-19 22:16:27
+2
A:
I was just talking about this with a friend. My suggestion would be to write a subclass of NSURLResponse. Something along these lines:
@interface MyHTTPURLResponse : NSURLResponse { NSDictionary *myDict; }
- (void)setAllHeaderFields:(NSDictionary *)dictionary;
@end
@implementation MyHTTPURLResponse
- (void)allHeaderFields { return myDict ?: [super allHeaderFields]; }
- (void)setAllHeaderFields:(NSDictionary *)dict { if (myDict != dict) { [myDict release]; myDict = [dict retain]; } }
@end
If you're dealing with an object you didn't make, you can try using object_setClass
to swizzle the class out. However I don't know if that will add the necessary instance variable. You could also use objc_setAssociatedObject
and stuff this all in a category instead, if you can support a new enough SDK.
Colin Barrett
2010-02-03 19:18:23