IOS 打开预览pdf、ppt、excel、word、tet、rtf、csv格式的文件,微信文件分享

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011154007/article/details/73549134
前言:打开预览pdf、ppt、excel、word、tet、rtf、csv格式的文件有两种一方,一种是利用 UIWebView或者WKWebView 来直接打开,另一种就是利用

QLPreviewController 来打开,但是现在这种方法只能打开本地文件,也就是说如果您是链接,那就需要将文件先下载下来,本文的重点主要讲述第二种方法。


步骤:

1、首先需要判断文件是否需要下载

#pragma mark 判断是否需要下载
- (void)isLoading
{
    NSString *urlStr = _urlStr;
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    NSString *path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/%lu.%@",(unsigned long)[urlStr hash],urlStr.pathExtension]];
    _path = path;
    NSData *data = [NSData dataWithContentsOfFile:path];
    
    if (data == nil) {
        [self writeToCacheWithUrl:urlStr];
    }
    
    [self addPreview];
}

2、是否需要写入缓存

#pragma mark 写入缓存
- (void)writeToCacheWithUrl:(NSString *)urlStr
{
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //获取document路径
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    [fileManager createDirectoryAtPath:[cachesPath stringByAppendingString:@"/Caches"] withIntermediateDirectories:YES attributes:nil error:nil];
    //写入路径
    NSString *path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/%lu.%@",(unsigned long)[urlStr hash],urlStr.pathExtension]];
    
    [data writeToFile:path atomically:YES];
}


3、接下来就是进入预览界面

- (void)addPreview
{
    QLPreviewController *qlPC = [[QLPreviewController alloc] init];
    qlPC.view.frame = CGRectMake(0, 64, self.view.width, self.view.height - 64);
    qlPC.dataSource = self;
    qlPC.delegate = self;
    [self addChildViewController:qlPC];
    [self.view addSubview:qlPC.view];
}

4、遵循<QLPreviewControllerDataSource,QLPreviewControllerDelegate方法

#pragma mark - previewControllerDataSource
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
    return 1;
}

- (id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
    //文件路径,也就是已经下载后的路径
    return [NSURL fileURLWithPath:_path];
}

5、预览完文件,可能需要进行分享,以下以微信分享为例

#pragma mark 分享
- (void)share
{
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = self.navigationItem.title;
    
    WXFileObject *fileObject = [WXFileObject object];
    fileObject.fileExtension = _urlStr.pathExtension;
    fileObject.fileData = [NSData dataWithContentsOfFile:_path];
    
    message.mediaObject = fileObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = 0;
    [WXApi sendReq:req];
}







阅读更多
换一批

没有更多推荐了,返回首页