AlexPaduraru
AlexPaduraru

Reputation: 31

change user agent multiple times

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

Upvotes: 1

Views: 368

Answers (2)

Tyzual Echizen
Tyzual Echizen

Reputation: 1

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];
    //...

Upvotes: 0

Leonardo
Leonardo

Reputation: 815

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?

Upvotes: 1

Related Questions