在程序中,有時(shí)候會(huì)從服務(wù)器下載一些文件來查看,比如word pdf文件,但是我們自己的應(yīng)用不具備查看此類文件的功能。蘋果給我們提供了DocumentInteractionViewController類,下面我們介紹這個(gè)類的如何使用,然后貼上自己的小demo供大家參考:
DocumentInteractionViewController demo
第一步:
創(chuàng)建DocumentInteractionViewController的實(shí)例,這其中就包含了你要打開那個(gè)文件的url,然后設(shè)定代理,實(shí)現(xiàn)代理方法,一會(huì)兒介紹代理方法的含義:
NSString *path = [[NSBundle mainBundle] pathForResource:@" 搭建React Native生態(tài)? 魏曉軍? 2016-06-24 " ofType:@"pdf"];
NSURL * url = [NSURL fileURLWithPath:path];
self.documentVC = [UIDocumentInteractionController interactionControllerWithURL:url];
self.documentVC.delegate = self;
第二步:介紹幾個(gè)此類的方法
1. 快速預(yù)覽,返回bool值,表示可不可以預(yù)覽
BOOL b = [self.documentVC presentPreviewAnimated:YES];
2. 彈出選項(xiàng)菜單由用戶自己選擇copy,print,quick look操作
BOOL b = [self.documentVC presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];
3. 通過item打開選項(xiàng),這里需要首先創(chuàng)建item
UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithTitle:@"打開文件" style:UIBarButtonItemStylePlain target:self action:@selector(itemAction:)];
self.navigationItem.leftBarButtonItem = item;
然后在item的點(diǎn)擊事件中,調(diào)用presentOptionsMenuFromBarButtonItem方法
- (void)itemAction:(UIBarButtonItem *)sender
{
NSLog(@"%@",NSStringFromSelector(_cmd));
[self.documentVC presentOptionsMenuFromBarButtonItem:sender animated:YES];
}
4. 通過其他應(yīng)用程序打開文件,如果沒有應(yīng)用程序可以打開,返回NO
BOOL result = [self.documentVC presentOpenInMenuFromRect:self.view.frame inView:self.view animated:YES];
if (!result) {
NSLog(@"沒有可以打開此文件的應(yīng)用");
}
5. 通過item讓其他應(yīng)用打開文件,如果沒有應(yīng)用程序可以打開,返回NO
類似第3步,先創(chuàng)建item,
UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(itemActionOpenInMenu:)];
self.navigationItem.rightBarButtonItem = item;
然后在item的點(diǎn)擊事件里,執(zhí)行第4步。
- (void)itemActionOpenInMenu:(UIBarButtonItem *)sender
{
NSLog(@"%@",NSStringFromSelector(_cmd));
BOOL result = [self.documentVC presentOpenInMenuFromRect:self.view.frame inView:self.view animated:YES];
if (!result) {
NSLog(@"沒有可以打開此文件的應(yīng)用");
}
}
第三步:介紹代理方法
#pragma mark 代理方法
//為快速預(yù)覽指定控制器
- (UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController*)controller
{
NSLog(@"%@",NSStringFromSelector(_cmd));
return self;
}
//為快速預(yù)覽指定View
- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller
{
NSLog(@"%@",NSStringFromSelector(_cmd));
return self.view;
}
//為快速預(yù)覽指定顯示范圍
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller
{
NSLog(@"%@",NSStringFromSelector(_cmd));
//? ? return self.view.frame;
return CGRectMake(0, 0, self.view.frame.size.width, 300);
}