我正在尝试创建一个非常简单的应用程序,它连接到一个 URL 并获取该 URL 的内容,在本例中是一个简单的 xml 文档。我的问题是请求似乎永远不会被发送。
我创建了一个从主文件运行的新项目(基础工具)。我已将 NSURLConnection 的委托设置为 self 并实现了必要的委托方法。问题是这些方法永远不会被调用。如果我将 URL 更改为一些虚假的 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;
}