User-Agent 정보를 변경하려고 해보니 다음과 같은 이슈가 있었다.


일반적으로 NSMutableURLRequest를 생성하고, 새로운 항목을 헤더에 추가하는 것은 이슈가 없다.


하지만, 기본적으로 헤더가 가지고 있는 항목인 User-Agent와 같은 경우는 기존의 값에 변경을 가하려면 이런 형태로는 수정한 값으로 반영이 되지 않는다.


    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];

    [request setValue:@"test" forHTTPHeaderField:@"test"];

    [_webView loadRequest:request];



검색을 해보니 NSUserDefault에 UserAgent 값으로 수정할 값을 적용하면, 이후의 헤더 값에 User-Agent가 원하는 형태로 적용이 된다는 것이었다.


    NSDictionary *userAgentDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"my user agent string",@"UserAgent", nil];

    [[NSUserDefaults standardUserDefaults] registerDefaults:userAgentDictionary];




그런데, 좀 문제가 발생했다.


웹뷰의 객체를 받아서 현재 웹뷰의 헤더 값을 읽어내고, NSUserDefault에 값을 적용하니 실제로 반영이 되지 않는 것이다. 웹뷰를 한 번 로드하면서 해당 값이 적용되어 버리는 듯이 보였다. 


그래서, 별도의 웹뷰 객체를 하나 생성해서 값을 얻어온 뒤에 저장하는 프로세스를 진행하고 현재의 웹뷰 컨트롤러의 웹뷰를 로드하니 내가 원하는 형태로 User-Agent가 저장되고 로드되었다.


- (void)setUserAgent {


    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];

    NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

    userAgent = [NSString stringWithFormat:@"%@ MY_APP_NAME", userAgent];

    

    NSDictionary *userAgentDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:userAgent,@"UserAgent", nil];

    [[NSUserDefaults standardUserDefaults] registerDefaults:userAgentDictionary];

    

    NSLog(@"userAgent: %@", userAgent);

}


이 형태의 함수를 앱 시작 시 호출하여 적용하니, 내가 원하는대로 기본 User-Agent에 앱 명을 추가한 형태로 로드 되었다.


*. 참조

1) Objective-C에서 설정 방법

http://stackoverflow.com/questions/478387/change-user-agent-in-uiwebview-iphone-sdk


2) Swift에서 설정 방법

http://stackoverflow.com/questions/26219997/how-can-i-set-the-user-agent-header-of-a-uiwebview-in-swift



+ Recent posts