views:

786

answers:

2

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
Doesn't that return an NSDictionary instead of an NSMutableDictionary?
Combat
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
I don't see how an immutable dictionary will help me modify the keys/values
Combat
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
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
+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