如何使NSURLConnection文件下载工作?

时间:2011-04-27 11:55:54

标签: iphone download nsurlconnection nsobject

我将ViewController声明为:

@interface DownloadViewController : UIViewController 
           <UITableViewDataSource, UITableViewDelegate>

我想用 NSURLConnection 下载文件。 NSURLConnection 只是“无法启动”,委托方法不起作用(例如,永远不会调用 connection:didReceiveResponse )。我在一些示例代码中注意到该类是子类NSObject而不是UIViewController

我如何组合它?我想使用ViewController方法但是我不能使用 NSURLConnection

找到一个完整解释的示例如何使用NSURLConnection下载文件并不是那么容易。每个人都只关注 didReceiveResponse 等简单的方法。

3 个答案:

答案 0 :(得分:3)

如果您遇到问题,可以考虑使用备受好评的ASIHTTPRequest library来管理您的下载。它会照顾你的一切。

例如,只需2行即可。

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:fullPathOfWhereToStoreFile];

答案 1 :(得分:3)

使用UIViewController而不是NSObject应该不是你的问题! 我在UIViewController中使用NSURLConnection没有问题! 这是我的代码的一部分(不确定它将按原样编译):

//
//  MyViewController.h
//

#import <Foundation/Foundation.h>

@interface MyViewController : UIViewController {
    @protected
    NSMutableURLRequest* req;
    NSMutableData* _responseData;
    NSURLConnection* nzbConnection;
}

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

@end

-

//
//  MyViewController.m
//

#import "MyViewController.h"

@implementation MyViewController

- (void)loadView {  
// create your view here
}

- (void) dealloc {
    [_responseData release];

    [super dealloc];
}

#pragma mark -

- (void)loadFileAtURL:(NSURL *)url {
    // allocate data buffer
    _responseData = [[NSMutableData alloc] init];

    // create URLRequest
    req = [[NSMutableURLRequest alloc] init];
    [req setURL:_urlToHandle];

    nzbConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
    [req release];
    req = nil;
}


#pragma mark -

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append data in the reception buffer
    if (connection == nzbConnection)
        [_responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if (connection == nzbConnection) {
        [nzbConnection release];
        nzbConnection = nil;

        // Print received data
        NSLog(@"%@",_responseData);

        [_responseData release];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // Something went wrong ...
    if (connection == nzbConnection) {
        [nzbConnection release];
        [_responseData release];
    }
}

@end

如果您打算下载大文件,请考虑将收到的数据包存储在文件中,而不是将其存储在内存中!

答案 2 :(得分:1)