2012-07-26 47 views
2

我無法將異步NSURLRequests發送到Ruby服務器。當我使用下面的連接從未:Objective-C到Ruby服務器的異步NSURLConnection

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服務需要自己的第三方框架,在這種情況下。

+0

你怎麼知道連接永遠不會被創建?你是否實現了NSURLConnection的委託方法? – rdelmar 2012-07-26 06:02:00

+0

服務器日誌沒有得到請求,除非完成同步請求,否則沒有響應字符串被髮送回程序。如果我簡單地將url更改爲php服務器,這裏看到的異步方法可以工作。 Ruby服務器似乎導致了這個問題。 – AddisDev 2012-07-26 06:14:57

+0

是的,所有的委託方法都實現了。 – AddisDev 2012-07-26 06:23:52

回答

6

你可以嘗試使用restkit API

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

感謝 尼基爾

+0

感謝您的快速響應。我發現restkit的安裝有點多,但它給了我一個嘗試ASIHTTPRequest完美工作的想法。 – AddisDev 2012-07-26 19:27:01

+2

嘗試AFNetworking。 – 2012-07-26 19:38:32