【发布时间】:2014-04-12 06:31:24
【问题描述】:
我正在尝试下载 pdf 文件。早些时候,当我使用完成处理程序块时,我能够在 tmp 位置看到文件。然后我想显示下载进度,所以我实现了委托方法。但我现在可以看到进度条正在工作并且正在下载文件。但是一旦下载完成(写入的字节数/总字节数 = 1),就会调用错误委托,并且 tmp 位置中没有文件。我错过了什么?下面是我的代码。我已将项目上传至https://www.dropbox.com/s/vn5zwfwx9izq60a/trydownload.zip
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:@"http://aayudham.com/URLLoadingSystem.pdf"]];
[downloadTask resume];
}
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"%@",[error localizedDescription]);
}
-(void) URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
dispatch_async(dispatch_get_main_queue(), ^{
_progressBar.progress = (double)totalBytesWritten/(double)totalBytesExpectedToWrite;
double value =(double)totalBytesWritten/(double)totalBytesExpectedToWrite;
NSLog(@"%f",value);
});
}
-(void) URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
}
-(void) URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
NSError *error;
//getting docs dir path
NSArray * tempArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [tempArray objectAtIndex:0];
//adding folder path
NSString *appDir = [docsDir stringByAppendingPathComponent:@"/Reader/"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:appDir])
{
[fileManager createDirectoryAtPath:appDir withIntermediateDirectories:NO attributes:nil error:&error];
}
BOOL fileCopied = [fileManager moveItemAtPath:[location path] toPath:[appDir stringByAppendingString:@"/demo.pdf"] error:&error];
NSLog(fileCopied ? @"Yes" : @"No");
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
【问题讨论】:
-
你登录
didCompleteWithError的错误是什么? -
当我打印
[error localizedDescription]时,我得到“操作无法完成。(Cocoa 错误 516。)”。 -
我可以通过在
toPath的末尾添加一个文件名来解决这个问题,现在它可以工作了。有没有其他有效的方法来做到这一点? -
不确定我是否理解,但也许只是生成一个 UUID 作为文件名就可以了...