2

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

下载器.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

下载器.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];
}
4

2 回答 2

3

你拼错了“receive”:

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

// Correct signature
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
于 2009-06-22T12:48:32.090 回答
0

您的 didReceiveData 方法的名称中有错字(i 在 e 之前,c 之后除外 :-)

因此,看起来您的类没有实现该(可选)选择器,它将被默默地忽略。

于 2009-06-22T12:49:54.800 回答