UIWebView自定义User-Agent让H5区分App来源

2017-07-19  本文已影响0人  吾乃常山赵子龙

方法:

<pre>
-(BOOL)changeUserAgent:(void(^)(void))callback{
NSString *addString=@"";
NSString *bundleID=[[NSBundle mainBundle] bundleIdentifier];

NSDictionary *bundleDic=[[NSBundle mainBundle] infoDictionary];
NSString *bundleVersion=[bundleDic objectForKey:@"CFBundleShortVersionString"];

if ([bundleID isEqualToString:@"com.transfar.TFHuoDiShipper"]) {
    addString=[NSString stringWithFormat:@" ehuodi ehuodiOwner/%@",bundleVersion];
}else if([bundleID isEqualToString:@"com.transfar.TFHuoDiDrivers"]){
    addString=[NSString stringWithFormat:@" ehuodi ehuodiDriver/%@",bundleVersion];
}
NSString *oldAgent = [self.commonWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
if ([oldAgent containsString:addString]) {
    return YES;
}

NSString *newAgent=@"";
if ([oldAgent containsString:@"ehuodi"]) {
    newAgent= [oldAgent stringByReplacingOccurrencesOfString:@" ehuodi.*$" withString:addString options:NSRegularExpressionSearch range:NSMakeRange(0, [oldAgent length])];
}else{
    newAgent=[oldAgent stringByAppendingString:addString];
}
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
if (callback) {
    callback();
    return NO;//返回NO则需要重新加载一次
}
return YES;

}

调用位置:

<pre>

(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
__weak typeof (self) weakSelf=self;
if([self changeUserAgent:^{
weakSelf.commonWebView=nil;
weakSelf.commonWebView.delegate=nil;
[weakSelf addWebView];
}]==NO){
return NO;
} return YES;
}
</pre>

效果:

<pre>
User-Agent Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13B143 EhuoDiShipper
</pre>

上一篇 下一篇

猜你喜欢

热点阅读