首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >networkManager for NSURLConnection

networkManager for NSURLConnection
EN

Stack Overflow用户
提问于 2014-02-27 15:07:48
回答 1查看 194关注 0票数 0

全,

我用几个ViewControllers创建了一个应用程序。在viewController中,我使用NSURLConnection从get服务器获取数据。现在,在每个ViewController中,我都用以下方式发布数据:

代码语言:javascript
复制
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.data.com/GetAllRequestsToPlay.php"]]];

NSString *post       = [NSString stringWithFormat:@"PI=%i",self.ownPlayer.playerID.intValue];
NSData   *postData   = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];

[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPShouldHandleCookies:YES];
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

//set post data of request
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

在每个viewController中,我都有以下方法:

  • -(NSURLConnection*)连接didReceiveData:(NSData *)数据{
  • -(NSURLConnection*)连接didFailWithError:(NSError *)错误{
  • -(void)connectionDidFinishLoading:(NSURLConnection *)连接{

这都是多余的,因为这些方法中的代码在每个viewController中都是相同的。

因此,我想创建一个模型类"connectionManager“,它在每个viewController中都用于完成所有的网络(发送帖子和处理响应)。

我有以下问题:

  • 是否有教程或示例代码如何创建?
  • 如何使响应在connectionManager中被捕获(因此"connection“方法)
  • 如何通知正确的viewController,数据已经接收,ViewController必须对数据做些什么?
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-27 15:18:44

创建一个只处理您的NSObject的NSURLConnections类。在这个类中,包含所有必需的委托,并添加一个NSNotification,以便在收到数据时通知其他类。

然后在每个需要的ViewController中实例化这个类,并侦听NSNotification处理接收的数据。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22072449

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档