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

方法:


-(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;

}

调用位置:

(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;
}

效果:


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

你可能感兴趣的:(UIWebView自定义User-Agent让H5区分App来源)