最近公司有这样需求:当用户用微信,qq或者其他app接Word,Ecxel,PDF文件时,选择打开方式时,自己的app能出现打开方式列表中,并能跳转到自己的app打开或者上传此类文件,解决办法如下:
以下只是示例,具体可以参考 https://developer.apple.com/library/content/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html#//apple_ref/doc/uid/TP40009259-SW1
部分代码参考自 http://stackoverflow.com/questions/15836145/associate-files-type-with-my-iphone-app
1.在info.plist文件作如下配置
- 1.1 新增 CFBundleDocumentTypes 这个key,它对应的value是一个字典数组,具体配置如下
CFBundleDocumentTypes
CFBundleTypeName
Molecules Structure File
CFBundleTypeIconFiles
[email protected]
icon.png
LSItemContentTypes
com.adobe.pdf
com.microsoft.word.doc
com.microsoft.excel.xls
CFBundleTypeRole
Viewer
LSHandlerRank
Owner
- 1.2 声明支持的文件类型和文件拓展名,新增UTExportedTypeDeclarations这个key,配置如下
UTExportedTypeDeclarations
UTTypeConformsTo
public.data
public.composite-content
UTTypeIdentifier
com.adobe.pdf
UTTypeDescription
PDF文档
UTTypeTagSpecification
public.mime-type
application/pdf
public.filename-extension
pdf
UTTypeConformsTo
public.data
UTTypeIdentifier
com.microsoft.word.doc
UTTypeDescription
Word文档
UTTypeTagSpecification
public.mime-type
application/msword
public.filename-extension
doc
docx
UTTypeConformsTo
public.data
UTTypeIdentifier
com.microsoft.excel.xls
UTTypeDescription
Excel Document
UTTypeTagSpecification
public.mime-type
application/vnd.ms-excel
public.filename-extension
xls
2.创建一个控制器用于处理这些文件,并在AppDelegate方法中作监听这些文件的打开
- 2.1 我是创建一个普通控制器QYFileReaderController,控制器的有一个UIWebView属性,用UIWebView就可以自动解析这些文件
- 2.2 QYFileReaderController对外暴露一个NSUrl类型的属性,用于接收这些文件的url
代码如下:
@interface QYFileReaderController : UIViewController
/** 文件绝对url */
@property (nonatomic,strong)NSURL *absoluteUrl;
@end
@interface QYFileReaderController ()
@property (weak, nonatomic) UIWebView *webView;
@end
@implementation QYFileReaderController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupWebView];
// 调用
[self.webView loadRequest:[NSURLRequest requestWithURL:self.absoluteUrl]];
}
- (void)setupWebView{
UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
self.webView = webView;
[self.view addSubview:self.webView];
// 自动适应大小
self.webView.scalesPageToFit = YES;
// 关闭弹簧效果
self.webView.scrollView.bounces = NO;
}
- 2.3 在AppDelegate的 (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url方法中监听这些文件的打开和获取对应文件的url,并传递url给QYFileReaderController
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
// NSLog(@"url:%@",url.absoluteString);
// NSLog(@"host:%@",url.host);
BOOL isLogin = YES; // 假设用户已登录
if (isLogin)
{
QYFileReaderController *readerVC = [[QYFileReaderController alloc] init];
readerVC.absoluteUrl = url;
UINavigationController *nav = self.window.rootViewController;
[nav pushViewController:readerVC animated:YES];
}
return YES;
}