繁体   English   中英

NSURLConnection委托方法没有被调用

[英]NSURLConnection delegate methods not getting called

我有一个具有NSURLConnection委托方法的服务器类。 我还有另一个名为SendRequest的类,它将把NSMutableURLRequest发送到服务器类。 在服务器类中,我有两种方法

- (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的方式与以前发送方式相同。 但是我不知道为什么它不起作用。 随意发表评论,但请帮助我。 我真的很担心

编辑:

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

我认为您对系统的描述与发布的代码不匹配,并且可以解释您所描述的问题。 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类的实例(同样,假定在其中实现委托方法)。 我认为第二个想法更糟,因为服务器已经知道如何启动请求。

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

NSURLConnectionDelegate设置为您的.h

然后在.m函数中运行以下代码

NSURLConnection *connection = [[NSURLConnection alloc] 
                                initWithRequest:request
                                       delegate:self startImmediately:NO];

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM