A typical User-Agent for an iPhone looks like
Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341
However, if I do
NSMutableURLRequest *newUserAgentRequest = (NSMutableURLRequest*)[NSURLRequest requestWithURL:self.url];
NSString *userAgent = [newUserAgentRequest valueForHTTPHeaderField:@"User-Agent"];
the User-Agent is `nil.
How do I intialize a request with a custom User-Agent?
Setting the User_Agent
(with an underscore) field works for some, but not all websites, and isn't usually overridden by the NSURL... classes. The other alternative, besides messing with the dictionary (which I believe is not allowed, but I'll post an example anyhow), is method swizzling.
+ (void)initialize {
// Set user agent (the only problem is that we can't modify the User-Agent later in the program)
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:@"Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341", @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
//only under MRC do we release [dictionnary release];
}