57

Hey I am using a NSURL Connection to receive data.

[NSURLConnection sendSynchronousRequest:
//create request from url
[NSURLRequest requestWithURL:
  //create url from string
  [NSURL URLWithString:url]
] 
//request parameters
returningResponse:nil error:nil
] 

Is it possible to change the user agent string? right now it is:

AppName/AppVersion CFNetwork/459 Darwin/10.0.0.d3

jantimon
  • 36,840
  • 23
  • 122
  • 185

2 Answers2

110

Obj-C:

NSString* userAgent = @"My Cool User Agent";
NSURL* url = [NSURL URLWithString:@"http://whatsmyuseragent.com/"];
NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]
                                autorelease];
[request setValue:userAgent forHTTPHeaderField:@"User-Agent"];

NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request
                                     returningResponse:&response
                                                 error:&error];

Swift:

let userAgent = "My Cool User Agent"
if let url = NSURL(string: "http://whatsmyuseragent.com/") {
   let request = NSMutableURLRequest(URL: url)
   request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
   var response:NSURLResponse? = nil;
   var error:NSError? = nil;
   if let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) {
      // do something with your data
   }
 }
udondan
  • 57,263
  • 20
  • 190
  • 175
nall
  • 15,899
  • 4
  • 61
  • 65
  • 4
    you should be using `setValue:forHTTPHeaderField:`, if you want to change the userAgent instead of just appending more information to the default one. – Daniel Oct 27 '14 at 11:09
6

Yes, you need to use an NSMutableURLRequest and set a custom header field for your user agent string.

Mike Abdullah
  • 14,933
  • 2
  • 50
  • 75
  • with 'swift' language there is no need to use NSMutableURLRequest because its overrided to single type of URLRequest – eemrah Feb 21 '22 at 18:01