ページ

Sunday, July 18, 2010

Change UserAgent on UIWebView ( Undocumented method )

I was looking for how to change the User Agent on UIWebView for iPhone/iPad.
then I found the solution... but it's undocumented method, which means it would be quite hard to get the approval from app store.


UIWebView+UserAgent.h

@interface UIWebView(UserAgent)
    -(void)setUserAgent:(NSString *)userAgent;
@end


UIWebView+UserAgent.m

#import "UIWebView+UserAgent.h"
#import <objc/runtime.h>

@implementation UIWebView(UserAgent)
-(void)setUserAgent:(NSString *)userAgent
{
    id webDocumentView;
    id newWebView;
    webDocumentView = objc_msgSend(self, @selector(_documentView));
    object_getInstanceVariable(webDocumentView, "_webView", (void**)&newWebView);
    objc_msgSend(newWebView, @selector(setCustomUserAgent:),userAgent);
}
@end


This would make the log analysis simpler by distinguishing precisely between Safari and the application on iPhone/iPad.
Plus, Providing some special services only for the application users on website is available by use of the UserAgent.

No comments:

Post a Comment