NSURLConnection 未启动

发布于 2024-07-18 13:48:46 字数 2786 浏览 8 评论 0原文

我正在尝试创建一个非常简单的应用程序,它连接到 URL 并获取该 URL 的内容,在本例中是一个简单的 xml 文档。 我的问题是该请求似乎永远不会被发送。

我创建了一个从主文件运行的新项目(基础工具)。 我已经设置了 将 NSURLConnection 委托给 self 并实现必要的委托方法。 问题是这些方法永远不会被调用。 即使我更改 URL 也没关系 到一些假的(如下例所示)。 在我看来,应用程序完成启动而无需发送或等待响应。 难道我的应用程序为请求创建了一个线程,然后不等待响应就完成了? 我知道该类正在运行,因为我收到了诸如“已创建连接”之类的 NSLOG 语句 “但委托方法中没有 NSLOG 语句。

我错过了什么?

#import "NetworkController.h"
@implementation NetworkController

- (id)init
{
    if(self = [super init])
    {

    }   
    return self;
}
- (void)dealloc
{
    NSLog(@"Calling dealloc");
    [super dealloc];
}
- (void) performConnection
{
    NSMutableData *receivedData;
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:
                                       @"http://www.test.php?some variables"]];

    NSMutableURLRequest *connectionRequest = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
    [url release];
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:connectionRequest delegate:self startImmediately:YES];

    if (!theConnection)
    {
        NSLog(@"Failed to submit request");
    }
    if(theConnection)
    {
        receivedData=[[NSMutableData data] retain];
        NSLog(@"Created connection.");

        NSLog(@"--------- Request submitted ---------");
        NSLog(@"receivedData: %@", receivedData);
    }

    [connectionRequest release];
}

#pragma mark NetworkController Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"Received response: %@", response);
    NSLog(@"Received response, connection retain count is %d",[connection retainCount]);
}

#pragma mark NetworkController Delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"Connection received data, retain count: %d", [connection retainCount]);
}

#pragma mark NetworkController Delegate
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"finished connection retain count:  %d", [connection retainCount]);}

#pragma mark NetworkController Delegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error receiving response: %@", error);
    [connection release];
}

@end

#import <Foundation/Foundation.h>
#import "NetworkController.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


    NetworkController *n = [[NetworkController alloc] init];
    n.performConnection;
    [n release];

    // insert code here...
    NSLog(@"Hello, World!");
    [pool drain];
    return 0;
}

I'm trying to create a very simple app which connects to an URL and gets the contents of that URL, in this case a simple xml document. My problem is that that the request never seems to gets sent.

I have created a new project(Foundation tool) which runs from a main file. I have set the
delegate of the NSURLConnection to self and implemented the necessary delegate methods.
The problem is that these methods never get called. It doesn't matter if I change the URL
to some bogus one(as in the example below).
It seems to me that the application finish launching without sending or waiting for the response.
Could it be that my application creates a thread for the request and then finishes without waiting for the response??
I know that the class is running since i get the NSLOG statements like "Created connection
" but no NSLOG statements from within the delegate methods.

What am I missing?

#import "NetworkController.h"
@implementation NetworkController

- (id)init
{
    if(self = [super init])
    {

    }   
    return self;
}
- (void)dealloc
{
    NSLog(@"Calling dealloc");
    [super dealloc];
}
- (void) performConnection
{
    NSMutableData *receivedData;
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:
                                       @"http://www.test.php?some variables"]];

    NSMutableURLRequest *connectionRequest = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
    [url release];
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:connectionRequest delegate:self startImmediately:YES];

    if (!theConnection)
    {
        NSLog(@"Failed to submit request");
    }
    if(theConnection)
    {
        receivedData=[[NSMutableData data] retain];
        NSLog(@"Created connection.");

        NSLog(@"--------- Request submitted ---------");
        NSLog(@"receivedData: %@", receivedData);
    }

    [connectionRequest release];
}

#pragma mark NetworkController Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"Received response: %@", response);
    NSLog(@"Received response, connection retain count is %d",[connection retainCount]);
}

#pragma mark NetworkController Delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"Connection received data, retain count: %d", [connection retainCount]);
}

#pragma mark NetworkController Delegate
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"finished connection retain count:  %d", [connection retainCount]);}

#pragma mark NetworkController Delegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error receiving response: %@", error);
    [connection release];
}

@end

#import <Foundation/Foundation.h>
#import "NetworkController.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


    NetworkController *n = [[NetworkController alloc] init];
    n.performConnection;
    [n release];

    // insert code here...
    NSLog(@"Hello, World!");
    [pool drain];
    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

稚然 2024-07-25 13:48:46

首先,消息语法是:

[n performConnection];

您所拥有的是属性访问语法。 而且由于该方法的类型为返回 void,因此即使在该级别上,我也不会认为它可以保证工作。

无论如何,主要问题是您正在使用异步 NSURLConnection API(好)但期望同步行为(坏)。 所有 NSURLConnection 方法都会立即返回,然后在后台工作,其想法是在事情发生时将委托消息发送到您的网络控制器 - 但在完成所有设置后,您立即释放网络控制器(进而泄漏连接,因为您没有在您的dealloc方法中释放它),然后退出。

您需要在释放网络控制器之前运行运行循环,以便为连接提供时间来发送请求、读取响应并向网络控制器发送一些委托消息。 您还需要在网络控制器的 dealloc 方法中取消释放连接。

另外,您需要将该 NSMutableData 变量设置为实例变量,因为您需要能够从委托方法访问它。 不要忘记在您的dealloc方法中也释放它(并在两个委托方法中将其释放并设置为nil)表示连接已结束)。

First, the message syntax is:

[n performConnection];

What you have there is property access syntax. And since the method is typed as returning void, I wouldn't take it as guaranteed to work even on that level.

Anyway, the major problem is that you're using the asynchronous NSURLConnection API (good) but expecting synchronous behavior (bad). All the NSURLConnection methods return immediately, then work in the background, with the idea sending delegate messages to your network controller as things happen—but immediately after you finish setting everything up, you release the network controller (in turn leaking the connection, since you didn't release it in your dealloc method), then exit.

You need to run the run loop before you release the network controller, to give the connection time to send the request, read the response, and send the network controller some delegate messages. You also need to cancel and release the connection in the network controller's dealloc method.

Also, you need to make that NSMutableData variable an instance variable, since you need to be able to reach it from the delegate methods. Don't forget to release that, too, in your dealloc method (and release it and set it to nil in both of the delegate methods that indicate the connection is over).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文