change user agent multiple times

时间秒杀一切 提交于 2019-12-24 15:59:35

问题


I am trying to toggle user agent for a uiwebview between iPhone and iPad. So to have a button that will change from iPad user agent to iPhone user agent and backward.

I found this link: http://www.mphweb.com/en/blog/easily-set-user-agent-uiwebview

Unfortunately, the user agent can be changed only once, even if I recreate the uiwebview.

Does anyone has an idea about how to do it?

Btw, I also tried set the user agent in urlrequest header, without success.

Thanks


回答1:


Me too, I have been able to set the UserAgent once only. Then I can't change it anymore. I tried on the simulator and on the device too. Same trouble.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSDictionary *dictionary = @{@"UserAgent" : @"MyOWnUserAgent_2"};
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
}

I don't use web views. I just make calls like:

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:urlRequest] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)

I cleaned, deleted the app from the device, I rebuilt, I quit, reboot, rebuilt... The problem is still there. I run XCode 7.3 (7D175) on OS X 10.11.5 (15F34) and build against Deploymen Target iOS 9.1, Base SDK iOS 9.3. Any clue?




回答2:


try this

static void appendUA(NSString *uaStr) {
    if (!uaStr)
        return;

    UIWebView *tempWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString *secretAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    secretAgent = [secretAgent stringByAppendingString:uaStr];
    NSDictionary<NSString *, id> *domain = [[NSUserDefaults standardUserDefaults] volatileDomainForName:NSRegistrationDomain];
    if (domain) {
        NSMutableDictionary<NSString *, id> *newDomain = [domain mutableCopy];
        [newDomain setObject:secretAgent forKey:@"UserAgent"];
        domain = newDomain;
    } else {
        domain = [[NSDictionary alloc]
                  initWithObjectsAndKeys:secretAgent, @"UserAgent", nil];
    }

    [[NSUserDefaults standardUserDefaults] removeVolatileDomainForName:NSRegistrationDomain];
    [[NSUserDefaults standardUserDefaults] setVolatileDomain:domain forName:NSRegistrationDomain];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

You should call this function BEFORE create WKWebview/UIWebView, and space is NOT automatically added.

    appendUA(@" ====TEST_UA====");
    WKWebView *wkWebView = [WKWebView new];
    //...


来源:https://stackoverflow.com/questions/15098321/change-user-agent-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!