objective-c - NSURLSessionDownloadTask - 下载但以错误结束

标签 objective-c nsurlsession

我正在尝试下载 pdf 文件。早些时候,当我使用完成处理程序 block 时,我能够在 tmp 位置看到该文件。然后我想显示下载进度,所以我实现了委托(delegate)方法。但我现在可以看到进度条正在工作并且正在下载文件。但是一旦下载完成(写入的字节数/总字节数 = 1),就会调用错误委托(delegate)并且 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

最佳答案

@Rob 感谢您的及时回复,这对我帮助很大。这是我的有效代码。希望它能帮助别人。我能够获取实际文件名并使用原始名称将文件移动到我的文档目录。

-(void) URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;

    //getting application's document directory path
    NSArray * tempArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsDir = [tempArray objectAtIndex:0];

    //adding a new folder to the documents directory path
    NSString *appDir = [docsDir stringByAppendingPathComponent:@"/Reader/"];

    //Checking for directory existence and creating if not already exists
    if(![fileManager fileExistsAtPath:appDir])
    {
        [fileManager createDirectoryAtPath:appDir withIntermediateDirectories:NO attributes:nil error:&error];
    }

    //retrieving the filename from the response and appending it again to the path
    //this path "appDir" will be used as the target path 
    appDir =  [appDir stringByAppendingFormat:@"/%@",[[downloadTask response] suggestedFilename]];

    //checking for file existence and deleting if already present.
    if([fileManager fileExistsAtPath:appDir])
    {
        NSLog([fileManager removeItemAtPath:appDir error:&error]?@"deleted":@"not deleted");
    }

    //moving the file from temp location to app's own directory
    BOOL fileCopied = [fileManager moveItemAtPath:[location path] toPath:appDir error:&error];
    NSLog(fileCopied ? @"Yes" : @"No");

}

关于objective-c - NSURLSessionDownloadTask - 下载但以错误结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22278407/

相关文章:

objective-c - 如何将(OS_dispatch_data *) 5018112字节转换成NSData放入UIImage

ios - 在 iOS 上,0x0000000000000026、0x000000000000001c、0x000000000000005a 是标记指针的示例吗?

ios - 我应该如何在 backgroundConfiguration 中使用 NSURLSession 将多个文件的 block 上传到 Amazon S3 ( iOS7 )

swift - 使用 contentsOfFile 参数创建 NSData 时指定文件偏移量

ios - NSURLSessionDownloadTask 在后台自动恢复所有任务

ios - 异步调用中的异步调用未执行

iphone - 打开持久连接

objective-c - Objective-C 和 Swift 之间的 URL 编码方法不一致

ios - 记录在设备上发送的 Objective-c 消息

不接受 Swift NSURLSession NSURLRequest Cookie