iOS设置自定义UA [NSUserDefaults standardUserDefaults] registerDefaults:@{ @"UserAgent":

【通常做法】

APP 内访问web view,通常需要带自定义UA,那么一般可以通过这个办法设置自定义UA

/* !!!: set UserAgent
 * 问题: 创建 NSMutableURLRequest 实例、设置 User-Agent,调用 UIWebView 的 loadRequest: 方法后,User-Agent 被系统替换;
 *  @see http://www.mphweb.com/en/blog/easily-set-user-agent-uiwebview
 */
+ (void)initialize {
    if (self == [WebViewController class]) {
        [[NSUserDefaults standardUserDefaults] registerDefaults:@{ @"UserAgent": [self userAgentWithWebView:[UIWebView new]] }];
    }
}

【特殊需求】

有些时候,考虑到兼容性,只对某些webview 实施自定义UA。那么,上面的办法显然不行了。+ (void)initialize在类创建的时候,只执行了一次。也就是所有的webview都带有自定义UA。那么,针对某一个webview实施自定义UA可以这么弄。这几个方法一定要是静态方法,要不然设置UA不生效

NSString* defaultUserAgent = nil;

/*
获取默认的UA,用于恢复UA
*/
+ (void)initialize {
    if (self == [WebViewController class]) {
        defaultUserAgent =  [[UIWebView new] stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    }
}

/*在默认UA后追加自定义UA*/
+ (void)registeCustomizeWebViewUserAgent {
    UIDevice *device = [UIDevice currentDevice];
    NSString *iOSName = [device systemName];
    NSString *iOSVersion = [device systemVersion];
    NSString *customizeUserAgent = [NSString stringWithFormat:@"xxxxxMobile/%@ (Platform/%@; %@/%@)", APP_SHORT_VERSION, @"iPad", iOSName, iOSVersion];

    NSString *webViewUserAgent = [[UIWebView new] stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    customizeUserAgent = [webViewUserAgent stringByAppendingFormat:@" %@", customizeUserAgent];
    if (customizeUserAgent) {
        [[NSUserDefaults standardUserDefaults] registerDefaults:@{ @"UserAgent": customizeUserAgent}];
    }
}
- (void)dealloc {
    /*由于自定义的userAgent无法播放webview的视频,所以。当webview销毁的时候,重置一下userAgent*/
    [[self class] recoverDefaultUserAgent];
}

+(void) recoverDefaultUserAgent{
    if (defaultUserAgent) {
        [[NSUserDefaults standardUserDefaults] registerDefaults:@{ @"UserAgent": defaultUserAgent}];
    }
}


你可能感兴趣的:(userAgent)