我有一个 ViewController 声明为:
@interface DownloadViewController : UIViewController
<UITableViewDataSource, UITableViewDelegate>
我想用NSURL连接下载文件。NSURL连接只是“无法启动”,委托方法不起作用(例如连接:didReceiveResponse从未被调用)。我在一些示例代码中注意到该类是子类化的NSObject
代替UIViewController
.
我该如何结合它?我想使用 ViewController 方法,但无法使用NSURL连接.
找到一个完整解释如何使用 NSURLConnection 下载文件的示例并不容易。每个人都只专注于简单的方法,例如didReceiveResponse.
使用 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
如果您打算下载大文件,请考虑将收到的数据包存储在文件中,而不是将其存储在内存中!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)