2

非同期NSURLRequestsをRubyサーバーに送信するのに問題があります。以下を使用すると、接続が確立されません。

self.data = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://domain.com/app/create_account.json"]];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request addValue:@"form-data" forHTTPHeaderField:@"Content-Disposition"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

ただし、最後の行を次のように交換すると、次のようになります。

NSData *returnData = [NSURLConnection sendSynchronousRequest:request   returningResponse:nil error:nil];

すべてがうまく機能します。しかし、私はこの接続を非同期的に行う必要があります...

編集-実例

NSURL *url = [NSURL URLWithString:@"http://domain.com/app/create_account.json"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:data forKey:@"data"];
[request setDelegate:self];
[request startAsynchronous];

この場合、RESTfulサービスには独自のサードパーティフレームワークが必要なようです。

4

1 に答える 1

6

restkitapiを使用してフォローしてみることができます

- (void)sendAsJSON:(NSDictionary*)dictionary {

RKClient *client = [RKClient clientWithBaseURL:@"http://restkit.org"];        

// create a JSON string from your NSDictionary 
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON];
NSError *error = nil;
NSString *json = [parser stringFromObject:dictionary error:&error];

// send your data
if (!error)
     [[RKClient sharedClient] post:@"/some/path" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self];
 }

参照:

  1. https://github.com/RestKit/RestKit/wiki/Tutorial-%3A-Introduction-to-RestKit
  2. https://github.com/RestKit/RestKit/wiki/Posting-NSDictionary-as-JSON

ありがとうNikhil

于 2012-07-26T08:56:58.600 に答える