Changing the userAgent of NSURLConnection

jantimon picture jantimon · Oct 7, 2009 · Viewed 38.8k times · Source

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

Answer

nall picture nall · Oct 7, 2009

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