经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » iOS » 查看文章
iOS文件预览分享小技能示例
来源:jb51  时间:2022/8/16 15:27:30  对本文有异议

前言

应用场景:文件下载、打印

I 第三方SDK分享文件

1.1 微信SDK

  1. /**
  2. enum WXScene {
  3. WXSceneSession = 0,
  4. WXSceneTimeline = 1,
  5. WXSceneFavorite = 2,
  6. };
  7. 文件真实数据内容
  8. * @note 大小不能超过10M
  9. */
  10. @property (nonatomic, retain) NSData *fileData;
  11. */
  12. - (void)sendFileContent
  13. {
  14. WXMediaMessage *message = [WXMediaMessage message];
  15. message.title = @"ML.pdf";
  16. message.description = @"Pro CoreData";
  17. [message setThumbImage:[UIImage imageNamed:@"res2.jpg"]];
  18. WXFileObject *ext = [WXFileObject object];
  19. ext.fileExtension = @"pdf";
  20. NSString* filePath = [[NSBundle mainBundle] pathForResource:@"ML" ofType:@"pdf"];
  21. ext.fileData = [NSData dataWithContentsOfFile:filePath];
  22. //+ (nullable instancetype)dataWithContentsOfURL:(NSURL *)url;
  23. message.mediaObject = ext;
  24. SendMessageToWXReq* req = [[[SendMessageToWXReq alloc] init]autorelease];
  25. req.bText = NO;
  26. req.message = message;
  27. req.scene = WXSceneSession;
  28. [WXApi sendReq:req completion:nil];
  29. }

1.2 友盟SDK

  1. #pragma mark - UMFileObject
  2. /*! @brief 多媒体消息中包含的文件数据对象
  3. *
  4. * @see UMShareObject
  5. */
  6. @interface UMShareFileObject : UMShareObject
  7. /** 文件后缀名
  8. * @note 长度不超过64字节
  9. */
  10. @property (nonatomic, retain) NSString *fileExtension;
  11. /** 文件真实数据内容
  12. * @note 大小不能超过10M
  13. */
  14. @property (nonatomic, retain) NSData *fileData;
  15. /** 文件的名字(不包含后缀)
  16. * @note 长度不超过64字节
  17. */
  18. @property (nonatomic, retain) NSString *fileName;
  19. @end

II 原生API的文件预览及其他应用打开

  1. - (BOOL)presentOptionsMenuFromRect:(CGRect)rect inView:(UIView *)view animated:(BOOL)animated;
  2. - (BOOL)presentOptionsMenuFromBarButtonItem:(UIBarButtonItem *)item animated:(BOOL)animated;
  3. // Bypasses the menu and opens the full screen preview window for the item at URL. Returns NO if the item could not be previewed.
  4. // Note that you must implement the delegate method documentInteractionControllerViewControllerForPreview: to preview the document.
  5. - (BOOL)presentPreviewAnimated:(BOOL)animated;//预览文件
  6. // Presents a menu allowing the user to open the document in another application. The menu
  7. // will contain all applications that can open the item at URL.
  8. // Returns NO if there are no applications that can open the item at URL.
  9. - (BOOL)presentOpenInMenuFromRect:(CGRect)rect inView:(UIView *)view animated:(BOOL)animated;//包括快速预览菜单、打印、复制
  10. - (BOOL)presentOpenInMenuFromBarButtonItem:(UIBarButtonItem *)item animated:(BOOL)animated;//不包括包括快速预览菜单
  • 获取NSURL
  1. //方式1:
  2. NSString* filePath = [[NSBundle mainBundle] pathForResource:@"ML" ofType:@"pdf"];
  3. NSURL *url = [NSURL fileURLWithPath:filePath];
  4. // 方式2
  5. //NSURL *url = [[NSBundle mainBundle] URLForResource:@"ML" withExtension:@"pdf"];
  • 实例化UIDocumentInteractionController
  1. UIDocumentInteractionController *documentController = [UIDocumentInteractionController interactionControllerWithURL:url];
  2. documentController.delegate = self;//UIDocumentInteractionControllerDelegate

2.1 预览文件

  1. [documentController presentPreviewAnimated:YES]; // 预览文件

2.2 文件分享

  1. CGRect rect = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
  2. [documentController presentOptionsMenuFromRect:rect inView:self.view animated:YES];//包括快速预览菜单、打印、复制
  3. // [documentController presentOpenInMenuFromRect:rect inView:self.view animated:YES];//不包括包括快速预览菜单

2.3 控制是否显示copy、 print、saveToCameraRoll

  1. #pragma mark - UIDocumentInteractionControllerDelegate
  2. - (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)interactionController{
  3. return self;
  4. }
  5. //
  6. /**
  7. print: saveToCameraRoll: copy:
  8. */
  9. - (BOOL)documentInteractionController:(UIDocumentInteractionController *)controller canPerformAction:(SEL)action{
  10. NSLog(@"canPerformAction %s %@ ", __func__,NSStringFromSelector(action));
  11. //NSStringFromSelector(_cmd) //当前选择器的名字
  12. // return NO;不显示copy print
  13. return YES;//显示copy print
  14. }
  15. - (BOOL)documentInteractionController:(UIDocumentInteractionController *)controller performAction:(SEL)action{
  16. NSLog(@"canPerformAction %s", __func__);
  17. return YES;//显示copy print
  18. // return NO;
  19. }

III 案例

3.1 文件下载和预览

  1. - (void)openfile:(CRMfilePreviewCellM*)m{
  2. // NSURL *relativeToURL = [NSURL URLWithString:m.url ];//必须先下载,否则无法查看文件内容
  3. [SVProgressHUD showWithStatus:@"加载中..."];
  4. NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:m.url]];
  5. [SVProgressHUD dismiss];
  6. if(data== nil){
  7. [SVProgressHUD showInfoWithStatus:@"文件下载失败"];
  8. return ;
  9. }
  10. // //用单例类 NSFileManager的对象,将文件写入本地
  11. NSFileManager *fileManage = [NSFileManager defaultManager];
  12. NSString *tmp = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  13. // NSString *tmp = NSTemporaryDirectory();
  14. NSString *fileName = m.fileName;
  15. tmp =[tmp stringByAppendingPathComponent:fileName];
  16. BOOL isSuccess = [fileManage createFileAtPath:tmp contents:data attributes:nil];
  17. if(isSuccess){
  18. NSURL *url = [NSURL fileURLWithPath:tmp];
  19. UIDocumentInteractionController *documentController = [UIDocumentInteractionController interactionControllerWithURL:url];
  20. //UIDocumentInteractionController delegate must implement documentInteractionControllerViewControllerForPreview: to allow preview
  21. documentController.delegate = self;//UIDocumentInteractionControllerDelegate
  22. [documentController presentPreviewAnimated:YES]; // 预览文件
  23. }
  24. }
  25. #pragma mark - UIDocumentInteractionControllerDelegate
  26. - (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)interactionController{
  27. return self;
  28. }
  29. //
  30. /**
  31. print: saveToCameraRoll: copy:
  32. */
  33. - (BOOL)documentInteractionController:(UIDocumentInteractionController *)controller canPerformAction:(SEL)action{
  34. NSLog(@"canPerformAction %s %@ ", __func__,NSStringFromSelector(action));
  35. //NSStringFromSelector(_cmd) //当前选择器的名字
  36. // return NO;不显示copy print
  37. return YES;//显示copy print
  38. }
  39. - (BOOL)documentInteractionController:(UIDocumentInteractionController *)controller performAction:(SEL)action{
  40. NSLog(@"canPerformAction %s", __func__);
  41. return YES;//显示copy print
  42. // return NO;
  43. }

3.2 使用数据模型保存下载文件路径

懒加载

  1. // NSURL *relativeToURL = [NSURL URLWithString:m.url ];//必须先下载,否则无法查看文件内容
  2. - (NSString *)filePathFromUrl{
  3. if(_filePathFromUrl !=nil){
  4. return _filePathFromUrl;
  5. }
  6. NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.url]];
  7. if(data== nil){
  8. [SVProgressHUD showInfoWithStatus:@"文件下载失败"];
  9. return nil;
  10. }
  11. // //用单例类 NSFileManager的对象,将文件写入本地
  12. NSFileManager *fileManage = [NSFileManager defaultManager];
  13. NSString *tmp = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  14. // NSString *tmp = NSTemporaryDirectory();
  15. NSString *fileName = self.fileName;
  16. tmp =[tmp stringByAppendingPathComponent:fileName];
  17. BOOL isSuccess = [fileManage createFileAtPath:tmp contents:data attributes:nil];
  18. _filePathFromUrl = tmp;
  19. if(!isSuccess){
  20. _filePathFromUrl = nil;
  21. }
  22. return _filePathFromUrl;
  23. }

预览文件

  1. - (void)openfile:(CRMfilePreviewCellM*)m{
  2. if(!m.filePathFromUrl){
  3. return;
  4. }
  5. NSURL *url = [NSURL fileURLWithPath:m.filePathFromUrl];
  6. UIDocumentInteractionController *documentController = [UIDocumentInteractionController interactionControllerWithURL:url];
  7. //UIDocumentInteractionController delegate must implement documentInteractionControllerViewControllerForPreview: to allow preview
  8. documentController.delegate = self;//UIDocumentInteractionControllerDelegate
  9. [documentController presentPreviewAnimated:YES]; // 预览文件
  10. }

3.3 使用数据模型分享文件

  1. @property (nonatomic,copy) NSString *fileName;
  2. @property (nonatomic,copy) NSString *url;
  3. //
  4. @property (nonatomic,copy) NSString *filePathFromUrl;
  5. /**
  6. /** 文件真实数据内容
  7. * @note微信文件分享 大小不能超过10M
  8. */
  9. @property (nonatomic, retain) NSData *fileData;
  10. - (void)sendFileContent;
  11. - (NSData *)fileData{
  12. if(_fileData==nil){
  13. NSString* filePath= [self filePathFromUrl];
  14. _fileData =[NSData dataWithContentsOfFile:filePath];
  15. }
  16. return _fileData;
  17. }
  18. - (void)sendFileContent
  19. {
  20. WXMediaMessage *message = [WXMediaMessage message];
  21. message.title = self.fileName;
  22. message.description =self.fileName;
  23. [message setThumbImage:[UIImage imageNamed:self.iconName]];
  24. WXFileObject *ext = [WXFileObject object];
  25. ext.fileExtension =self.fileExtension;
  26. ext.fileData =self.fileData;
  27. //+ (nullable instancetype)dataWithContentsOfURL:(NSURL *)url;
  28. message.mediaObject = ext;
  29. SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
  30. req.bText = NO;
  31. req.message = message;
  32. req.scene = WXSceneSession;
  33. [WXApi sendReq:req completion:nil];
  34. }

3.4 清理缓存

获取沙盒缓存路径

  1. + (nullable NSString *)userCacheDirectory {
  2. NSArray<NSString *> *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  3. return paths.firstObject;
  4. }

清理沙河文件缓存

  1. - (void)removeAllData {
  2. [self.fileManager removeItemAtPath:self.diskCachePath error:nil];
  3. [self.fileManager createDirectoryAtPath:self.diskCachePath
  4. withIntermediateDirectories:YES
  5. attributes:nil
  6. error:NULL];
  7. }

清理WKWebView的缓存

  1. + (void)clearWebCacheCompletion:(dispatch_block_t)completion {
  2. if (@available(iOS 9.0, *)) {
  3. NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
  4. NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
  5. [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:completion];
  6. } else {
  7. NSString *libraryDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
  8. NSString *bundleId = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
  9. NSString *webkitFolderInLib = [NSString stringWithFormat:@"%@/WebKit",libraryDir];
  10. NSString *webKitFolderInCaches = [NSString stringWithFormat:@"%@/Caches/%@/WebKit",libraryDir,bundleId];
  11. NSString *webKitFolderInCachesfs = [NSString stringWithFormat:@"%@/Caches/%@/fsCachedData",libraryDir,bundleId];
  12. NSError *error;
  13. /* iOS8.0 WebView Cache path */
  14. [[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCaches error:&error];
  15. [[NSFileManager defaultManager] removeItemAtPath:webkitFolderInLib error:nil];
  16. /* iOS7.0 WebView Cache path */
  17. [[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCachesfs error:&error];
  18. if (completion) {
  19. completion();
  20. }
  21. }
  22. }

清理图片缓存

  1. +(void)clearCache:(NSString *)path{
  2. NSFileManager *fileManager=[NSFileManager defaultManager];
  3. if ([fileManager fileExistsAtPath:path]) {
  4. NSArray *childerFiles=[fileManager subpathsAtPath:path];
  5. for (NSString *fileName in childerFiles) {
  6. //如有需要,加入条件,过滤掉不想删除的文件
  7. NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
  8. [fileManager removeItemAtPath:absolutePath error:nil];
  9. }
  10. }
  11. // [[SDImageCache sharedImageCache] cleanDisk];
  12. [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
  13. }];
  14. }

以上就是iOS文件预览分享小技能示例的详细内容,更多关于iOS文件预览分享的资料请关注w3xue其它相关文章!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号