这里是最low的采用webview方式打开的, 网上还有其他方式,就不一一列举了,直说我遇到的坑,而且网上没有说明的地方
1,首先在info.plish文件,
添加如下:
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>pdf</string>
</array>
<key>CFBundleTypeIconFiles</key>
<array>
<string>copy.png</string>
</array>
<key>CFBundleTypeName</key>
<string>Files</string>
<key>LSHandlerRank</key>
<string>Default</string>
<key>LSItemContentTypes</key>
<array>
<string>com.adobe.pdf</string>
</array>
</dict>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>pdf</string>
</array>
<key>CFBundleTypeIconFiles</key>
<array/>
<key>LSHandlerRank</key>
<string>Default</string>
<key>Document Content Type UTIs</key>
<array>
<string>com.adobe.pdf</string>
</array>
</dict>
</array>
这时候,你在选择应用的时候, 就会发现你的应用出现在了列表中,
2,打开文件
在Appdelegate中,添加如下
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
if (url != nil) {
NSString *path = [url absoluteString];
NSMutableString *string = [[NSMutableString alloc] initWithString:path];
if ([path hasPrefix:@"file://"]) {
[string replaceOccurrencesOfString:@"file://" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, path.length)];
}
[[NSNotificationCenter defaultCenter] postNotificationName:@"pdf" object:string];
}
return YES;
}
在创建的显示文件的viewcontroller中,
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(opening:) name:@"pdf" object:nil];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"pdf" object:nil];
}
- (void)opening:(NSNotification *)notifacation
{
self.webview = [[UIWebView alloc] initWithFrame:self.view.bounds];
NSString *str = notifacation.object;
//注意:此行代码为防止文件名称为中文,造成打开文件报错,进行转码
NSString *dataGBK = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *pdfURL = [NSURL fileURLWithPath:dataGBK];
NSURLRequest *request = [NSURLRequest requestWithURL:pdfURL];
[self.webview setScalesPageToFit:YES];
[self.webview loadRequest:request];
[self.view addSubview:self.webview];
}
注意 如果你打开的是中文名称的PDF文件报错了 请添加如下代码
//将路径中的utf8码转为中文字符
NSString *dataGBK = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];