NSURLConnection不会调用didRecieveData方法

时间:2009-06-22 11:56:45

标签: iphone nsurlconnection downloading

我希望我的应用程序在iPhone SDK文档中从互联网上下载一些数据 我找到NSURLConnection类,用于下载,我是对的吗? 我在文档中编写了相同的代码并运行它。连接已成功创建,但未下载任何数据。在一两秒后触发connectionDidFinishLoading但结果中没有数据。问题是,didRecieveData方法永远不会被触发。我不知道为什么,我搜索了互联网,但每个结果都与文档中的代码相同。你能给个建议吗?谢谢你的每一个回复 我的下载类源代码如下。

Downloader.h

@interface Downloader : NSObject {
    NSURLConnection *conn;

    //Array to hold recieved data
    NSMutableData *recievedData;
}

@property (nonatomic, retain) NSURLConnection *conn;
@property (nonatomic, retain) NSMutableData *recievedData;

- (void)downloadContentsOfUrl:(NSURL *)url;

@end

Downloader.m

#import "Downloader.h"
@implementation Downloader
@synthesize recievedData, conn;

- (void)connection:(NSURLConnection *)connection didRecieveResponse:(NSURLResponse *)response
{
    NSLog(@"did recieve response");

    [recievedData release];
    recievedData = nil;
}

- (void)connection:(NSURLConnection *)connection didRecieveData:(NSData *)data
{
    NSLog(@"did recieve data");
    //Append the new data to the recieved data
    [recievedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    //Release the connection and the data object
    [connection release];
    [recievedData release];

    NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //ToDo with data
    //[recievedData writeToFile:@"data" atomically:YES];
    NSLog(@"downloaded");
    NSLog(@"%u", [recievedData length]);
    //Release the connection and the data object
    [connection release];
    [recievedData release];
}

- (void)downloadContentsOfUrl:(NSURL *)url
{
    //Create the connection
    //Create the request
    NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:url 
            cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

        //Create the connection with the request and start loading the data
    conn =  [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self 
                startImmediately:YES];
    if(conn)
    {
        //Create the NSMutableData that will hold the recieve data
        recievedData = [[NSMutableData data] retain];
        NSLog(@"Connection success!");
    }
    else
    {
        NSLog(@"Can't download this file!");
    }       
}

- (void)dealloc
{
    [conn release];
    [recievedData release];

    [super dealloc];
}

2 个答案:

答案 0 :(得分:3)

你拼错了“收到”:

// Your signature
- (void)connection:(NSURLConnection *)connection didRecieveData:(NSData *)data;

// Correct signature
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

答案 1 :(得分:0)

你的didReceiveData方法名称中有一个拼写错误(我在e之前,除了c: - 之外)

因此,看起来你的类没有实现那个(可选的)选择器,它会被默默地忽略。