Obromios Obromios - 1 year ago 241
Android Question

How to set a custom header for webView requests in react-native

I want to be able to detect on my ruby on rails server side that a http request has come from a webView component in my app. The app is using react-native. In particular, I want to distinguish between a request from the app and a request from mobile safari running on an ios device.

I have tried setting the following in the


NSURL *url = [NSURL URLWithString:@"http://localhost:3000/signin"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request addValue:@"GolfMentor" forHTTPHeaderField:@"User-Agent"];
[request addValue:@"GolfMentor" forHTTPHeaderField:@"X-MY-CUSTOM-HEADER"];
NSLog(@"%@", [request allHTTPHeaderFields]);

and the output in the console is

GolfMentor[63924:12437749] {
"User-Agent" = GolfMentor;
"X-MY-CUSTOM-HEADER" = GolfMentor;

So the customer header appears to be set. However, when I view the request header in my ruby on rails app, there is no sign of the custom header. It looks like my changes are being overwritten latter in the execution of the react-native app. So where and how should I set the custom header? I am also interested in do the same thing for an android version of the app?

Answer Source

Try adding the following lines to AppDelegate.m to set the custom user-agent

NSString *newAgent = @"GolfMentor";
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

A fuller answer and the solution for android can be found here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download