Reputation: 3159
I have a webview app tool, which essentially consists of the webview and two buttons on a toolbar. One button to view the source of the page, and another button to view/change the current User Agent.
I have both functions working on iOS 5 (view source, and change User Agent), but I cant seem to grab the User Agent in iOS 4.x.
I'm using the following now:
userAgentViewController.UAText = [self.webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
This works in iOS5, but in iOS 4.x, it doesnt return anything. Is there a way to achieve the same functionality in iOS 4.x?
Thank you!
Upvotes: 1
Views: 3192
Reputation: 2992
Try this in the AppDelegate.m
+ (void)initialize
{
// Set user agent (the only problem is that we can’t modify the User-Agent later in the program)
// iOS 5.1
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:@”Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B176 Safari/7534.48.3”, @”UserAgent”, nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
}
Upvotes: 0
Reputation: 12213
to get the useragent, check the HTTP header in the NSURLRequest of your response. You can retreive this one in the webViewDidFinishLoad delegate method.
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(@"%@", [[webView request] valueForHTTPHeaderField: @"User-Agent"]);
}
to set it, you have to custom an NSMutableURLRequest and give it to your webView
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"yourwebsite.com"]];
[request setHTTPMethod:@"POST"];
[request setValue:USERAGENT_STRING forHTTPHeaderField: @"User-Agent"];
[webView loadRequest:request];
[request release];
and that's it !
Upvotes: 3