NSURLConnection委托方法未被调用

时间:2012-05-04 14:48:28

标签: iphone ios cocoa delegates nsurlconnection

我有一个服务器类,它具有NSURLConnection的委托方法。我正在使用另一个名为SendRequest的类,它将NSMutableURLRequest发送到Server Class。 在服务器类中,我有两个名为

的方法
- (void)executeAsync:(NSMutableURLRequest)urlRequest timeOutInterval:(int)timeOut
{
    _urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];];
}

- (void)executeSync:(NSMutableURLRequest)urlRequest
{
    NSData* respData = [NSURLConnection sendSynchronousRequest:urlRequest                        returningResponse:&response error:&error];

}

一切正常,直到这里,我能够从SendRequest类调用上面的executeAsync方法,该类调用委托方法。

现在我在SendRequest类中添加了一个新方法,它将调用Server类中的executeRequest方法。

- (void)executeRequest:(NSMutableURLRequest)urlRequest
{
    _urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];];
}

这一次,我被困了。调用executeRequest方法但在处理URL请求时没有调用其委托方法。我被震惊了好几个小时。

一切似乎都是正确的,我发送urlRequest的方式与之前发送的方式相同。但我不知道为什么它不起作用。感觉免费评论,但请帮助我。我真的很担心

编辑:

我需要向服务器发送请求并获得响应。如果我尝试使用同步它工作正常,但它阻止主线程。这就是我要进行异步的原因。通过委托方法,我试图获取响应数据。

3 个答案:

答案 0 :(得分:1)

我认为您对系统的描述与发布的代码不符,它解释了您描述的问题。 SendRequest类应该依赖Server类来执行服务器请求。

看起来SendRequest类将连接委托设置为self。我猜这些委托方法都是在Server类上实现的。

尝试做你的描述建议......

// SendRequest.m

- (void)executeRequest:(NSMutableURLRequest)urlRequest
{
    // however you get ahold of your server...
    Server *myServer = [Server sharedInstance];

    // let it do the work.  it has the delegate methods
    [myServer executeAsync:urlRequest];
}

或者,SendRequest代码可以保持原样,但将委托设置为Server类的实例(再次,假设代理方法的实现位置)。我认为这第二个想法更糟糕,因为服务器已经知道如何启动请求。

答案 1 :(得分:-1)

我终于解决了它。希望这对一些人有所帮助。我使代码清理并正确地声明了方法,最后在为类创建对象时,我必须使用initwithDelegate:self。最后调用NSURLConnection委托方法。

答案 2 :(得分:-1)

NSURLConnectionDelegate 设置为.h

然后在.m函数

中运行以下代码
NSURLConnection *connection = [[NSURLConnection alloc] 
                                initWithRequest:request
                                       delegate:self startImmediately:NO];

[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] 
                      forMode:NSDefaultRunLoopMode];
[connection start];