iOS从入门到放弃ios实用开发技巧

iOS实现下载文件并预览(例如:word文件)

2017-05-24  本文已影响72人  ZIM东东

提前注释:下载方法出处在哪,我就不得而知了,不得而知了
我是复制项目里的代码,陈年往事不在查出处了,
看到的伙伴如果看到了原文,请联系我,我及时注明,🙏
-------分隔线----------
文章里的代码块,可直接复制到程序里使用
增加如下代理:

NSURLSessionDownloadDelegate,UIWebViewDelegate,UIDocumentInteractionControllerDelegate
/**
 *  下载任务
 */
@property (nonatomic, strong) NSURLSessionDownloadTask* downloadTask;
/**
 *  resumeData记录下载位置
 */
@property (nonatomic, strong) NSData* resumeData;
/**
 *  session
 */
@property (nonatomic, strong) NSURLSession* session;

源生session网络请求,点击方法里写👇这段代码,开始下载文件

//分解下载,大文件时使用
            NSURL* url = [NSURL URLWithString:noteModel.contractFileUrl];
            // 创建任务
            self.downloadTask = [self.session downloadTaskWithURL:url];
            // 开始任务
            [self.downloadTask resume];

session的懒加载

- (NSURLSession *)session
{
    if (nil == _session) {
        
        NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
        self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

下载完毕会调用NSURLSessionDownloadDelegate

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    // response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致
    NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    
    // 将临时文件剪切或者复制Caches文件夹
    NSFileManager *mgr = [NSFileManager defaultManager];
    
    // AtPath : 剪切前的文件路径
    // ToPath : 剪切后的文件路径
    //location  文件临时地址
    [mgr moveItemAtPath:location.path toPath:file error:nil];

    [Utils hideLoding:self.view];
/*
    // 提示下载完成
    [[[UIAlertView alloc] initWithTitle:@"下载完成" message:downloadTask.response.suggestedFilename delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil] show];
    */
    //文件路径
    NSString *cachePath = file;
/*
 /var/mobile/Containers/Data/Application/--/Library/Caches/888.docx
下面这段代码是调起预览
 */
    UIDocumentInteractionController *documentController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:cachePath]];
    
    documentController.delegate = self;
 
    //直接显示预览
    [documentController presentPreviewAnimated:YES];
    //显示包含预览的菜单项
    //[documentController presentOptionsMenuFromRect:CGRectZero inView:self.view animated:YES];
    //显示不包含预览菜单项
    [documentController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
    
}

在这里面监听下载进度,totalBytesWritten/totalBytesExpectedToWrite
每次写入沙盒完毕调用
bytesWritten 这次写入的大小
totalBytesWritten 已经写入沙盒的大小
totalBytesExpectedToWrite 文件总大小

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten
                        totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
   // NSLog((@"\n[函数名:%s]\n" "[行号:%d]\n" "%f\n"), __FUNCTION__, __LINE__,(double)totalBytesWritten/totalBytesExpectedToWrite);
    
}

👇调用预览的代理方法

- (UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController*)controller
{
    return self;
}
- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller
{
    return self.view;
}
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller
{
    return self.view.frame;
}

点击预览窗口的“Done”(完成)按钮时调用

- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController*)_controller
{
}
上一篇下一篇

猜你喜欢

热点阅读