1

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

4

2 回答 2

1

我也是,我只能设置一次 UserAgent。那我就不能再改了。我也在模拟器和设备上试过。同样的麻烦。

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

我不使用网络视图。我只是打这样的电话:

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

我清理,从设备中删除应用程序,我重建,我退出,重新启动,重建......问题仍然存在。我在 OS X 10.11.5 (15F34) 上运行 XCode 7.3 (7D175) 并针对 Deploymen Target iOS 9.1、Base SDK iOS 9.3 进行构建。有什么线索吗?

于 2016-07-26T16:27:01.723 回答
0

尝试这个

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

您应该在创建 WKWebview/UIWebView之前调用此函数,并且不会自动添加空间。

    appendUA(@" ====TEST_UA====");
    WKWebView *wkWebView = [WKWebView new];
    //...
于 2018-03-08T08:43:19.940 回答