更改NSURLConnection的userAgent

嗨,我正在使用NSURL连接来接收数据。

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

是否有可能更改用户代理string? 现在是:

AppName / AppVersion CFNetwork / 459 Darwin / 10.0.0.d3

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]; 

迅速:

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

是的,您需要使用NSMutableURLRequest并为您的用户代理string设置自定义标题字段。