• iOS OC开发,文件的下载、预览


    /// 下载/打开

    - (void)downloadActionWithDownloadString:(NSString *)downloadString{

        //url : 下载地址

        NSString *url;

        if ([downloadString containsString:@"?"]) {

            NSRange range = [downloadString rangeOfString:@"?"];

            url = [downloadString substringToIndex:range.location];

        }else{

            url = downloadString;

        }

        //suffix : 后缀.zip .doc

        NSString * suffix = [url pathExtension];

        NSMutableArray *tempArray = [NSMutableArray arrayWithArray:[url  componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/."]]];//@",!"以,或!切割,而不是把,!连在一起当成一个整体进行切割

        NSInteger count = tempArray.count-2;

        NSString *preName = tempArray[count];

        

        //name : 文件名XXX.zip

        NSString * name = [NSString stringWithFormat:@"%@.%@", preName,suffix];

        

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *documentsDirectory = [paths lastObject];

        NSFileManager *fileManager = [NSFileManager defaultManager];

        //创建一个本地沙盒文件,便于日后管理,比如删除

        NSString * filesPath = [documentsDirectory stringByAppendingPathComponent:@"files"];

        if (![[NSFileManager defaultManager] fileExistsAtPath:filesPath]) {

            /// 创建一个文件

            BOOL success =  [[NSFileManager defaultManager] createDirectoryAtPath:filesPath withIntermediateDirectories:YES attributes:nil error:nil];

            NSLog(@"success:%d", success);

        }

        //filepath :下载后的文件本地路径

        NSString *filePath = [filesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@", name]];

        if ([fileManager fileExistsAtPath:filePath]) {

            //文件已经存在,直接打开

            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否打开文件" message:nil preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction * cancelAction  =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];

            

            [alertController addAction:cancelAction];

            

            [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {

                [self openDocxWithPath:filePath];

            }]];

            

            [self presentViewController:alertController animated:YES completion:nil];

            

        }else {

            //文件不存在,要下载

            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否下载并打开文件" message:nil preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction * cancelAction  =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];

            

            [alertController addAction:cancelAction];

            

            [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {

                [self downloadDocxWithFilePath:filePath downloadString:downloadString];

            }]];

            

            [self presentViewController:alertController animated:YES completion:nil];

            

        }

    }

    /**

     下载文件

     @param filePath 文件本地路径

     @param downloadString 文件下载地址

     */

    -(void)downloadDocxWithFilePath:(NSString *)filePath downloadString:(NSString *)downloadString{

        

        NSString *urlString = downloadString;

        NSURL * url = [NSURL URLWithString:urlString];

        NSURLRequest *request = [NSURLRequest requestWithURL:url];

        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

        NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

            

            NSLog(@"%lld   %lld",downloadProgress.completedUnitCount,downloadProgress.totalUnitCount);

            NSLog(@"下载中....");

        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

            

            return [NSURL fileURLWithPath:filePath];  //这里返回的是文件下载到哪里的路径 要注意的是必须是携带协议file://

        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {

            

            NSString *name = [filePath path];

            [self openDocxWithPath:name];

        }];

        [task resume];

        

    }

    /**

     打开文件

     @param filePath 文件路径

     */

    -(void)openDocxWithPath:(NSString *)filePath {

        UIDocumentInteractionController *doc= [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];

        doc.delegate = self;

        [doc presentPreviewAnimated:YES];

        // 打开的过程有点慢

    }

    #pragma mark - UIDocumentInteractionControllerDelegate

    //必须实现的代理方法 预览窗口以模式窗口的形式显示,因此需要在该方法中返回一个view controller ,作为预览窗口的父窗口。如果你不实现该方法,或者在该方法中返回 nil,或者你返回的 view controller 无法呈现模式窗口,则该预览窗口不会显示。

    - (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{    

        return self;

    }

    - (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller {    

        return self.view;

    }

    - (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller {    

        return CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height);

    }

  • 相关阅读:
    C#基础系列——一场风花雪月的邂逅:接口和抽象类
    C#进阶系列——动态Lamada(二:优化)
    C#进阶系列——动态Lamada
    JS组件系列——Bootstrap Table 表格行拖拽(二:多行拖拽)
    JS组件系列——Bootstrap Table 表格行拖拽
    C#进阶系列——DDD领域驱动设计初探(七):Web层的搭建
    C#进阶系列——MEF实现设计上的“松耦合”(四):构造函数注入
    C#进阶系列——DDD领域驱动设计初探(六):领域服务
    C#进阶系列——DDD领域驱动设计初探(五):AutoMapper使用
    C#进阶系列——DDD领域驱动设计初探(四):WCF搭建
  • 原文地址:https://www.cnblogs.com/lrr0618/p/13470086.html
Copyright © 2020-2023  润新知