iOS 调起第三方程序打开文件 ( UIDocumentInteractionController )

项目中有个下载文件功能,下载后需要能查看,总不能为每一种类型的文件写个查看功能吧.

好在iOS有个UIDocumentInteractionController ,可以帮你调起手机上已安装的应用来查看文件.


首先要配置一下info.plist文件,告诉系统哪些类型的文件需要使用UIDocumentInteractionController来打开

也可以用在代码里设置UTI这个属性,我没试过哈,

plist里面可以一波带走,简单省事

总结一下差不多就这些吧:

<key>CFBundleDocumentTypes</key>

<array>

<dict>

<key>CFBundleTypeName</key>

<string>com.myapp.common-data</string>

<key>LSHandlerRank</key>

<string>Default</string>

<key>LSItemContentTypes</key>

<array>

<string>com.microsoft.powerpoint.ppt</string>

<string>public.item</string>

<string>com.microsoft.word.doc</string>

<string>com.adobe.pdf</string>

<string>com.microsoft.excel.xls</string>

<string>public.image</string>

<string>public.content</string>

<string>public.composite-content</string>

<string>public.archive</string>

<string>public.audio</string>

<string>public.movie</string>

<string>public.text</string>

<string>public.data</string>

</array>

</dict>

</array>

直接粘到info.plist就可以了.

先遵守这个代理协议:UIDocumentInteractionControllerDelegate

然后是代码部分:

// 拿到下载的文件路径 
NSString *filePath = [[LGDownloadManager sharedInstance] getFilePathWithURL:fileModel.url];;
if (filePath == nil) return;
// 转成URL
NSURL *url = [NSURL fileURLWithPath:filePath];
    
if (url) {
        
    self.documentVC = [UIDocumentInteractionController interactionControllerWithURL:url];
    [self.documentVC setDelegate:self];
    BOOL canOpen =  [self.documentVC presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
        
    // 返回NO说明没有可以打开该文件的爱屁屁, 友情提示一下
    if (canOpen == NO) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有找到可以打开该文件的应用" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}

填坑: self.documentVC这个对象只在这一处用了, 我直接 UIDocumentInteractionController *documentVC = .....  不就行了.

我一开始就是这么干的,既然提了,那结果可想而知,还是太年轻了.

为什么不行嘞?  

documentVC对像如果不被引用,出了大括号就被释放掉了,都成nil了,自然是弹不出来的,所有他必须作为self的一个成员变量被引用才能保证不被过早释放掉







  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值