0

I'm looking to send an NSDictionary up to a server running Django, and I would prefer if I had to do little or no work writing an encoder/parser.

Is there an easy way to accomplish this task?

4

2 に答える 2

0

iOS はワンライナーでこれを行うことをサポートしていませんが、次のようにすることができます。

@interface NSString (URLEncoding)

- (NSString *)urlEncodedUTF8String;

@end

@interface NSURLRequest (DictionaryPost)

+ (NSURLRequest *)postRequestWithURL:(NSURL *)url
                          parameters:(NSDictionary *)parameters;

@end

@implementation NSString (URLEncoding)

- (NSString *)urlEncodedUTF8String {
  return (id)CFURLCreateStringByAddingPercentEscapes(0, (CFStringRef)self, 0,
    (CFStringRef)@";/?:@&=$+{}<>,", kCFStringEncodingUTF8);
}

@end

@implementation NSURLRequest (DictionaryPost)

+ (NSURLRequest *)postRequestWithURL:(NSURL *)url
                          parameters:(NSDictionary *)parameters {

  NSMutableString *body = [NSMutableString string];

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  [request setHTTPMethod:@"POST"];
  [request addValue:@"application/x-www-form-urlencoded"
           forHTTPHeaderField:@"Content-Type"];

  for (NSString *key in parameters) {
    NSString *val = [parameters objectForKey:key];
    if ([body length])
      [body appendString:@"&"];
    [body appendFormat:@"%@=%@", [[key description] urlEncodedUTF8String],
                                 [[val description] urlEncodedUTF8String]];
  }
  [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
  return request;
}

@end

次に、次のように簡単です。

NSURL *url = [NSURL URLWithString:@"http://posttestserver.com/post.php"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
    [NSNumber numberWithInt:42], @"number",
    @"apple", @"brand", nil];
NSURLRequest *request = [NSURLRequest postRequestWithURL:url parameters:params];
[NSURLConnection sendAsynchronousRequest:request queue:nil completionHandler:nil];

この例では、応答を気にしていないことに注意してください。それが気になる場合は、ブロックを提供して、それで何かを行うことができます。

于 2012-05-25T19:03:40.547 に答える