這里是最low的采用webview方式打開的, 網(wǎng)上還有其他方式,就不一一列舉了,直說我遇到的坑,而且網(wǎng)上沒有說明的地方
1,首先在info.plish文件,
屏幕快照 2017-12-04 下午2.09.13.png
添加如下:
<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>
這時候,你在選擇應(yīng)用的時候, 就會發(fā)現(xiàn)你的應(yīng)用出現(xiàn)在了列表中,
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;
}
在創(chuàng)建的顯示文件的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;
//注意:此行代碼為防止文件名稱為中文,造成打開文件報錯,進行轉(zhuǎn)碼
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文件報錯了 請?zhí)砑尤缦麓a
//將路徑中的utf8碼轉(zhuǎn)為中文字符
NSString *dataGBK = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];