Objective-C异步连接到Ruby服务器
向Ruby服务器发送异步NSURL请求时遇到问题。当我使用以下选项时,永远不会建立连接:Objective-C异步连接到Ruby服务器,objective-c,ruby,asynchronous,nsurlconnection,restkit,Objective C,Ruby,Asynchronous,Nsurlconnection,Restkit,向Ruby服务器发送异步NSURL请求时遇到问题。当我使用以下选项时,永远不会建立连接: self.data = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:@"http://domain.c
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服务似乎需要自己的第三方框架 您可以使用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];
}
-(void)sendAsJSON:(NSDictionary*)字典{
RKClient*client=[RKClient clientWithBaseURL:@”http://restkit.org"];
//从NSDictionary创建JSON字符串
id parser=[[RKParserRegistry sharedRegistry]ParserFormetype:RKPimetypeJSON];
n错误*错误=nil;
NSString*json=[parser stringFromObject:字典错误:&错误];
//发送您的数据
如果(!错误)
[[RKClient sharedClient]post:@/some/path”参数:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding]MimetType:RKMIMETypeJSON]委托:self];
}
参考:
谢谢
Nikhil你怎么知道从未建立过连接?您是否实现了NSURLConnection的委托方法?除非同步请求完成,否则服务器日志不会收到任何请求,也不会将响应字符串发送回程序。如果我简单地将url更改为php服务器,这里看到的异步方法就可以工作。Ruby服务器似乎导致了这个问题。是的,所有委托方法都已实现。为什么不试试rest工具包:-)谢谢您的快速响应。我发现restkit的安装有点太多了,但它让我想到尝试一个运行完美的httprequest。