我需要从服务器下载大文件(即 > 40MB)到我的应用程序,该文件将是 ZIP 或 PDF。我使用 NSURLConnection 实现了它,如果文件较小,它会很好地工作,否则它会下载一部分填充并且执行已停止。例如,我尝试下载 36MB 的 PDF 文件,但只下载了 16MB。请帮我知道原因?如何解决?
仅供引用: 实现文件
#import "ZipHandlerV1ViewController.h"
@implementation ZipHandlerV1ViewController
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)viewDidLoad
{
UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 400, 400)];
[mainView setBackgroundColor:[UIColor darkGrayColor]];
UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[downloadButton setFrame:CGRectMake(50, 50, 150, 50)];
[downloadButton setTitle:@"Download File" forState:UIControlStateNormal];
[downloadButton addTarget:self action:@selector(downloadFileFromURL:) forControlEvents:UIControlEventTouchUpInside];
[mainView addSubview:downloadButton];
[self setRequestURL:@"http://www.mobileveda.com/r_d/mcps/optimized_av_allpdf.pdf"];
[self.view addSubview:mainView];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void) setRequestURL:(NSString*) requestURL {
url = requestURL;
}
-(void) downloadFileFromURL:(id) sender {
NSURL *reqURL = [NSURL URLWithString:url];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:reqURL];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error !" message:@"Error has occured, please verify internet connection" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *fileName = [[[NSURL URLWithString:url] path] lastPathComponent];
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [pathArr objectAtIndex:0];
NSString *filePath = [folder stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *writeError = nil;
[webData writeToURL: fileURL options:0 error:&writeError];
if( writeError) {
NSLog(@" Error in writing file %@' : \n %@ ", filePath , writeError );
return;
}
NSLog(@"%@",fileURL);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error !" message:@"Error has occured, please verify internet connection.." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
@end
头文件:
#import <UIKit/UIKit.h>
@interface ZipHandlerV1ViewController : UIViewController {
NSMutableData *webData;
NSString *url;
}
-(void) setRequestURL:(NSString*) requestURL;
@end
谢谢,
更新: 发生这种情况是因为我的可下载文件位于具有下载限制的共享主机中。在我将该文件移动到工作正常的专用服务器之后。而且我还尝试从其他一些网站下载一些其他文件,例如视频,也可以正常工作。 所以,如果你遇到部分下载的问题,不要只看代码,还要检查服务器
最佳答案
您目前将所有下载的数据保存在一个 NSMutableData 对象中,该对象保存在您设备的 RAM 中。根据设备和可用内存的不同,这将在某个时候触发内存警告甚至崩溃。
要使如此大的下载工作,您必须将所有下载的数据直接写入文件系统。
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//try to access that local file for writing to it...
NSFileHandle *hFile = [NSFileHandle fileHandleForWritingAtPath:self.localPath];
//did we succeed in opening the existing file?
if (!hFile)
{ //nope->create that file!
[[NSFileManager defaultManager] createFileAtPath:self.localPath contents:nil attributes:nil];
//try to open it again...
hFile = [NSFileHandle fileHandleForWritingAtPath:self.localPath];
}
//did we finally get an accessable file?
if (!hFile)
{ //nope->bomb out!
NSLog("could not write to file %@", self.localPath);
return;
}
//we never know - hence we better catch possible exceptions!
@try
{
//seek to the end of the file
[hFile seekToEndOfFile];
//finally write our data to it
[hFile writeData:data];
}
@catch (NSException * e)
{
NSLog("exception when writing to file %@", self.localPath);
result = NO;
}
[hFile closeFile];
}
关于iphone - NSURLConnection 下载大文件(>40MB),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6215095/