IOS iPhone/iPad – Get User-Agent for UIWebView

In each new version of iOS the browser gets a new user-agent string. I’ve been searching for a way to get the user-agent string from the API but haven’t been able to find a straight forward way to do it. Here’s my solution:
WebViewUserAgent.h
#import <Foundation/Foundation.h>
 
@interface WebViewUserAgent : NSObject <UIWebViewDelegate> {
 NSString *userAgent;
 UIWebView *webView;
}
@property (nonatomic, retain) NSString *userAgent;
-(NSString*)userAgentString;
@end
 
WebViewUserAgent.m 
#import "WebViewUserAgent.h"
 
 
@implementation WebViewUserAgent
@synthesize userAgent;
 
-(NSString*)userAgentString
{
 webView = [[UIWebView alloc] init];
 webView.delegate = self;
 [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:
                                                             @"www.google.com"]]];
 
 // Wait for the web view to load our bogus request and give us the 
                                                                secret user agent.
 while (self.userAgent == nil) 
 {
  // This executes another run loop. 
  [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:
                                                            [NSDate distantFuture]];
 }
 
 return self.userAgent;
}
 
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:
                               (NSURLRequest *)request navigationType:
                                             (UIWebViewNavigationType)navigationType
{
 self.userAgent = [request valueForHTTPHeaderField:@"User-Agent"];
 
 // Return no, we don't care about executing an actual request.
 return NO;
}
 
- (void)dealloc 
{
 [webView release];
 [userAgent release];
 [super dealloc];
}
@end
Using the class is simple:
WebViewUserAgent *agent = [[WebViewUserAgent alloc] init];
NSLog(@"User-agent: %@", [agent userAgentString]);
[agent release]; 

Comments

Popular posts from this blog

LINUX Move and copy files using SSH

PHP Predefined Variables

Java : Variables Declaring