hemant
hemant

Reputation: 195

Getting and setting user-agent in uiwebview in iphone?

i am trying to display an image from a url into my UIWebview but the image size is too small to be displayed without making it blurred by stretching it..Since i cannot auto-resize the image(as it gets blurred) i was thinking of getting and setting user-agent value for iphone...But i m not able to find much relevant info about it and i am also not sure if it'll work or not?? anybody having any idea how it can be accomplished??

Upvotes: 1

Views: 3664

Answers (2)

Nate
Nate

Reputation: 31045

To get the User-Agent, you can try using javascript like this or as in the answer from @cem, you can implement webView:shouldStartLoadWithRequest:navigationType: and then read the header field from the request object passed to your UIWebViewDelegate:

[request valueForHTTPHeaderField:@"User-Agent"];

For setting, however, the UIWebViewDelegate method did not work for me with iOS 5. Maybe it did in the past.

What worked for me was actually to define an application-wide user default for the UserAgent key (that's not a typo ... there's no hyphen between the words User and Agent).

In my app delegate, I used an initializer, to get this value set before any UIWebViews or NSURLRequests were created:

+ (void) initialize {
    // TODO: put in whatever custom user agent you want here:
    NSString* userAgent = @"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19";

    NSDictionary* initDefaults = [[NSDictionary alloc] initWithObjectsAndKeys:
                                  userAgent, @"UserAgent",
                                  nil];

    [[NSUserDefaults standardUserDefaults] registerDefaults:initDefaults];  
}

Note: if you're not using ARC, remember to release initDefaults in the snippet above.

Upvotes: 0

cem
cem

Reputation: 3321

If you implement a UIWebViewDelegate class, you can fetch the Request with webView:shouldStartLoadWithRequest:navigationType: – at this point you should be able to manipulate the Request, something like

[request setValue:@"your custom useragent" forHTTPHeaderField:@"User-Agent"];

Upvotes: 1

Related Questions