본문 바로가기
옛날

UIWebView에서 user Agent 변경 [IOS]

by 차가운게 조아 2015. 12. 17.


iOS 5 이상

AppDelegate.m 파일에 아래 코드를 넣으면 됩니다.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   NSString *deviceModel = [[UIDevice currentDevice].model stringByReplacingOccurrencesOfString:@"" withString:@""];
    NSString *userAgent = [NSString stringWithFormat:@"Mozilla/5.0 (%@; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9A334,webView_iphone",deviceModel];
    NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:userAgent,@"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
    [dictionnary release];

    .....   
    .....
}

본인은 스마트폰에서 모바일웹으로 접속한 것인지 앱에서 웹뷰로 접속한 것인지 구분하기 위해
UserAgent 맨 뒤에 ,webView_iphone  문자열을 삽입하였습니다.

확인은 웹뷰를 구현한 곳에서 아래처럼 출력하시면 확인 할 수 있습니다
-(BOOL) webView:(UIWebView*) webView shouldStartLoadWithRequest:(NSURLRequest*) req navigationType:(UIWebViewNavigationType) navigationType{
    NSMutableURLRequest *request = (NSMutableURLRequest *)req;
    
    NSLog(@"%@",[request allHTTPHeaderFields]);
    ....
    ....
}


http://blog.suromind.com/94