Posted By

gfazioli on 03/09/11


Tagged

NSDictionary POSTNSMutableURLRequest


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

terababy
athanhcong
Tintenklecks


Send POST parameters


 / Published in: Objective C
 

URL: http://www.undolog.com

  1. - (BOOL)connectionPOST:(NSURLRequest *)aRequest
  2. withParams:(NSDictionary *)aDictionary {
  3.  
  4. if ([aDictionary count] > 0) {
  5. initWithURL:[aRequest URL]];
  6. [request setHTTPMethod:@"POST"];
  7.  
  8. NSMutableString *postString = [[NSMutableString alloc] init];
  9. NSArray *allKeys = [aDictionary allKeys];
  10. for (int i = 0; i < [allKeys count]; i++) {
  11. NSString *key = [allKeys objectAtIndex:i];
  12. NSString *value = [aDictionary objectForKey:key];
  13. [postString appendFormat:( (i == 0) ? @"%@=%@" : @"&%@=%@" ), key, value];
  14. }
  15.  
  16. [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
  17.  
  18. [NSURLConnection connectionWithRequest:request delegate:self];
  19.  
  20. [postString release];
  21. postString = nil;
  22.  
  23. [request release];
  24. request = nil;
  25.  
  26. return YES;
  27. } else {
  28. return NO;
  29. }
  30. }
  31.  
  32. // ---------------------------------------------
  33. // usage
  34.  
  35. NSURL *url = [NSURL URLWithString:@"http://www.undolog.com"];
  36. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  37.  
  38. // Send name=Mark&lastname=Smith
  39. NSDictionary *params = [[NSDictionary alloc]
  40. initWithObjectsAndKeys:
  41. @"Mark", @"name",
  42. @"Smith", @"lastname", nil];
  43. [self connectionPOST:request withParams:params];
  44. [params release];
  45. params = nil;

Report this snippet  

You need to login to post a comment.