Changing the userAgent of NSURLConnection

IphoneCocoaCocoa TouchNsurlconnection

Iphone Problem Overview


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

Iphone Solutions


Solution 1 - Iphone

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

Solution 2 - Iphone

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjantimonView Question on Stackoverflow
Solution 1 - IphonenallView Answer on Stackoverflow
Solution 2 - IphoneMike AbdullahView Answer on Stackoverflow