欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS修改UserAgent

程序员文章站 2022-05-09 13:51:01
...

由于特殊需求,有时候需要给UserAgent添加相应的内容,一般都是尾部添加:

-(void)registUserAgent{
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSLog(@"old agent :%@", oldAgent);
    NSString *newAgent;
    if (![oldAgent hasSuffix:@"yonglian"]) {
        newAgent = [oldAgent stringByAppendingString:@" yonglian"];
    }else{
        newAgent = oldAgent;
    }
    //add my info to the new agent
    NSLog(@"new agent :%@", newAgent);
    
    //regist the new agent
    NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
复制代码

添加最好是在程序启动的时候:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
}
复制代码

亲测,其他方式都不管用,只能在一开始就添加。

转载于:https://juejin.im/post/5ce4f5b86fb9a07ea33bec44