文件缓存预览查看

#import <QuickLook/QuickLook.h>

@interface VC()<QLPreviewControllerDataSource,QLPreviewControllerDelegate>

@property (nonatomic,strong)NSURL *fileURL; //文件预览路径

-(void)showFilewithUrlString:(NSString*)string{
    NSURL *targetURL = [NSURL URLWithString:string];
    NSString *docPath = [self documentsDirectoryPath];
    NSString *pathToDownloadTo = [NSString stringWithFormat:@"%@/%@", docPath, [targetURL lastPathComponent]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL hasDownLoad= [fileManager fileExistsAtPath:pathToDownloadTo];
    if (!hasDownLoad) {
        NSData *fileData = [[NSData alloc] initWithContentsOfURL:targetURL];
        // Get the path to the App's Documents directory
//        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//        NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
//        NSString *pathToDownloadTo = [NSString stringWithFormat:@"%@/%@", docPath, [targetURL lastPathComponent]];
        BOOL bol = [fileData writeToFile:pathToDownloadTo atomically:YES];
        NSLog(@"文件缓存:%@ \n结果:%d",pathToDownloadTo,bol);
        self.fileURL = [NSURL fileURLWithPath:pathToDownloadTo];
    }
    QLPreviewController *qlVC = [QLPreviewController new];
    qlVC.delegate = self;
    qlVC.dataSource = self;
    [self presentViewController:qlVC animated:YES completion:nil];
}

- (NSString *)documentsDirectoryPath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [paths objectAtIndex:0];
    return documentsDirectoryPath;
}

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

- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    return self.fileURL;
}

 

posted @ 2021-04-21 18:43  frounk  阅读(102)  评论(0编辑  收藏  举报