美文网首页
UIWebView自定义User-Agent让H5区分App来源

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

作者: 吾乃常山赵子龙 | 来源:发表于2017-07-19 18:33 被阅读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>

相关文章

网友评论

      本文标题:UIWebView自定义User-Agent让H5区分App来源

      本文链接:https://www.haomeiwen.com/subject/ekqrkxtx.html